aboutsummaryrefslogtreecommitdiffstats
path: root/consensus/dexcon/fake_dexcon.go
blob: befda75140363af7f0c6ec071f54fbf3e85a9c68 (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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package dexcon

import (
    "crypto/ecdsa"
    "math/big"

    coreCommon "github.com/dexon-foundation/dexon-consensus/common"
    dexCore "github.com/dexon-foundation/dexon-consensus/core"
    coreCrypto "github.com/dexon-foundation/dexon-consensus/core/crypto"
    coreDKG "github.com/dexon-foundation/dexon-consensus/core/crypto/dkg"
    coreEcdsa "github.com/dexon-foundation/dexon-consensus/core/crypto/ecdsa"
    coreTypes "github.com/dexon-foundation/dexon-consensus/core/types"
    coreTypesDKG "github.com/dexon-foundation/dexon-consensus/core/types/dkg"
    coreUtils "github.com/dexon-foundation/dexon-consensus/core/utils"

    "github.com/dexon-foundation/dexon/common"
    "github.com/dexon-foundation/dexon/consensus"
    "github.com/dexon-foundation/dexon/core/types"
    "github.com/dexon-foundation/dexon/core/vm/evm"
    "github.com/dexon-foundation/dexon/crypto"
    "github.com/dexon-foundation/dexon/rlp"
)

type FakeDexcon struct {
    *Dexcon
    nodes *NodeSet
}

func NewFaker(nodes *NodeSet) *FakeDexcon {
    return &FakeDexcon{
        Dexcon: New(),
        nodes:  nodes,
    }
}

func (f *FakeDexcon) Prepare(chain consensus.ChainReader, header *types.Header) error {
    var coreBlock coreTypes.Block
    if err := rlp.DecodeBytes(header.DexconMeta, &coreBlock); err != nil {
        return err
    }

    blockHash, err := coreUtils.HashBlock(&coreBlock)
    if err != nil {
        return err
    }

    parentHeader := chain.GetHeaderByNumber(header.Number.Uint64() - 1)
    var parentCoreBlock coreTypes.Block
    if parentHeader.Number.Uint64() != 0 {
        if err := rlp.DecodeBytes(
            parentHeader.DexconMeta, &parentCoreBlock); err != nil {
            return err
        }
    }

    randomness := f.nodes.Randomness(header.Round, common.Hash(blockHash))
    coreBlock.Randomness = randomness

    dexconMeta, err := rlp.EncodeToBytes(&coreBlock)
    if err != nil {
        return err
    }
    header.DexconMeta = dexconMeta
    return nil
}

type Node struct {
    cryptoKey coreCrypto.PrivateKey
    ecdsaKey  *ecdsa.PrivateKey

    id                  coreTypes.NodeID
    dkgid               coreDKG.ID
    address             common.Address
    prvShares           *coreDKG.PrivateKeyShares
    pubShares           *coreDKG.PublicKeyShares
    receivedPrvShares   *coreDKG.PrivateKeyShares
    recoveredPrivateKey *coreDKG.PrivateKey
    signer              *coreUtils.Signer
    txSigner            types.Signer

    mpk *coreTypesDKG.MasterPublicKey
}

func newNode(privkey *ecdsa.PrivateKey, txSigner types.Signer) *Node {
    k := coreEcdsa.NewPrivateKeyFromECDSA(privkey)
    id := coreTypes.NewNodeID(k.PublicKey())
    return &Node{
        cryptoKey: k,
        ecdsaKey:  privkey,
        id:        id,
        dkgid:     coreDKG.NewID(id.Bytes()),
        address:   crypto.PubkeyToAddress(privkey.PublicKey),
        signer:    coreUtils.NewSigner(k),
        txSigner:  txSigner,
    }
}

func (n *Node) ID() coreTypes.NodeID    { return n.id }
func (n *Node) DKGID() coreDKG.ID       { return n.dkgid }
func (n *Node) Address() common.Address { return n.address }

func (n *Node) MasterPublicKey(round uint64) *coreTypesDKG.MasterPublicKey {
    mpk := &coreTypesDKG.MasterPublicKey{
        ProposerID:      n.ID(),
        Round:           round,
        DKGID:           n.DKGID(),
        PublicKeyShares: *n.pubShares,
    }

    if err := n.signer.SignDKGMasterPublicKey(mpk); err != nil {
        panic(err)
    }
    return mpk
}

func (n *Node) DKGMPKReady(round uint64) *coreTypesDKG.MPKReady {
    ready := &coreTypesDKG.MPKReady{
        ProposerID: n.ID(),
        Round:      round,
    }

    if err := n.signer.SignDKGMPKReady(ready); err != nil {
        panic(err)
    }
    return ready
}

func (n *Node) DKGFinalize(round uint64) *coreTypesDKG.Finalize {
    final := &coreTypesDKG.Finalize{
        ProposerID: n.ID(),
        Round:      round,
    }

    if err := n.signer.SignDKGFinalize(final); err != nil {
        panic(err)
    }
    return final
}

func (n *Node) CreateGovTx(nonce uint64, data []byte) *types.Transaction {
    tx, err := types.SignTx(types.NewTransaction(
        nonce,
        evm.GovernanceContractAddress,
        big.NewInt(0),
        uint64(2000000),
        big.NewInt(1e10),
        data), n.txSigner, n.ecdsaKey)
    if err != nil {
        panic(err)
    }
    return tx
}

type NodeSet struct {
    signer    types.Signer
    privkeys  []*ecdsa.PrivateKey
    nodes     map[uint64][]*Node
    crs       map[uint64]common.Hash
    signedCRS map[uint64][]byte
}

func NewNodeSet(round uint64, signedCRS []byte, signer types.Signer,
    privkeys []*ecdsa.PrivateKey) *NodeSet {
    n := &NodeSet{
        signer:    signer,
        privkeys:  privkeys,
        nodes:     make(map[uint64][]*Node),
        crs:       make(map[uint64]common.Hash),
        signedCRS: make(map[uint64][]byte),
    }
    n.signedCRS[round] = signedCRS
    n.crs[round] = crypto.Keccak256Hash(signedCRS)
    return n
}

func (n *NodeSet) Nodes(round uint64) []*Node {
    if nodes, ok := n.nodes[round]; ok {
        return nodes
    }
    panic("dkg not ready")
}

func (n *NodeSet) CRS(round uint64) common.Hash {
    if c, ok := n.crs[round]; ok {
        return c
    }
    panic("crs not exist")
}

func (n *NodeSet) SignedCRS(round uint64) []byte {
    if c, ok := n.signedCRS[round]; ok {
        return c
    }
    panic("signedCRS not exist")
}

// Assume All nodes in NodeSet are in DKG Set too.
func (n *NodeSet) RunDKG(round uint64, threshold int) {
    var ids coreDKG.IDs
    var nodes []*Node
    for _, key := range n.privkeys {
        node := newNode(key, n.signer)
        nodes = append(nodes, node)
        ids = append(ids, node.DKGID())
    }

    for _, node := range nodes {
        node.prvShares, node.pubShares = coreDKG.NewPrivateKeyShares(threshold)
        node.prvShares.SetParticipants(ids)
        node.receivedPrvShares = coreDKG.NewEmptyPrivateKeyShares()
    }

    // exchange keys
    for _, sender := range nodes {
        for _, receiver := range nodes {
            // no need to verify
            prvShare, ok := sender.prvShares.Share(receiver.DKGID())
            if !ok {
                panic("not ok")
            }
            receiver.receivedPrvShares.AddShare(sender.DKGID(), prvShare)
        }
    }

    // recover private key
    for _, node := range nodes {
        privKey, err := node.receivedPrvShares.RecoverPrivateKey(ids)
        if err != nil {
            panic(err)
        }
        node.recoveredPrivateKey = privKey
    }

    // store these nodes
    n.nodes[round] = nodes
}

func (n *NodeSet) Randomness(round uint64, hash common.Hash) []byte {
    if round == 0 {
        return []byte{}
    }
    return n.TSig(round, hash)
}

func (n *NodeSet) SignCRS(round uint64) {
    var signedCRS []byte
    if round < dexCore.DKGDelayRound {
        signedCRS = crypto.Keccak256(n.signedCRS[round])
    } else {
        signedCRS = n.TSig(round, n.crs[round])
    }
    n.signedCRS[round+1] = signedCRS
    n.crs[round+1] = crypto.Keccak256Hash(signedCRS)
}

func (n *NodeSet) TSig(round uint64, hash common.Hash) []byte {
    var ids coreDKG.IDs
    var psigs []coreDKG.PartialSignature
    for _, node := range n.nodes[round] {
        ids = append(ids, node.DKGID())
    }
    for _, node := range n.nodes[round] {
        sig, err := node.recoveredPrivateKey.Sign(coreCommon.Hash(hash))
        if err != nil {
            panic(err)
        }
        psigs = append(psigs, coreDKG.PartialSignature(sig))
        // ids = append(ids, node.DKGID())

        // FIXME: Debug verify signature
        pk := coreDKG.NewEmptyPublicKeyShares()
        for _, nnode := range n.nodes[round] {
            p, err := nnode.pubShares.Share(node.DKGID())
            if err != nil {
                panic(err)
            }
            err = pk.AddShare(nnode.DKGID(), p)
            if err != nil {
                panic(err)
            }
        }

        recovered, err := pk.RecoverPublicKey(ids)
        if err != nil {
            panic(err)
        }

        if !recovered.VerifySignature(coreCommon.Hash(hash), sig) {
            panic("##########can not verify signature")
        }
    }

    sig, err := coreDKG.RecoverSignature(psigs, ids)
    if err != nil {
        panic(err)
    }
    return sig.Signature
}