-
Notifications
You must be signed in to change notification settings - Fork 5
/
registerAsProducer.go
98 lines (85 loc) · 2.39 KB
/
registerAsProducer.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
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
package bft
import (
"errors"
"github.com/drep-project/DREP-Chain/chain/store"
"github.com/drep-project/DREP-Chain/chain/transactions"
"github.com/drep-project/DREP-Chain/crypto"
"github.com/drep-project/DREP-Chain/types"
"github.com/drep-project/binary"
)
var (
MinerPrefix = []byte("miner")
_ = (transactions.ITransactionSelector)((*RegisterAsProducerTransactionSelector)(nil))
_ = (transactions.ITransactionValidator)((*RegisterAsProducerTransactionExecutor)(nil))
)
// ***********DEPLOY**************//
type RegisterAsProducerTransactionSelector struct{}
func (registerAsProducerTransactionSelector *RegisterAsProducerTransactionSelector) Select(tx *types.Transaction) bool {
return tx.Type() == types.RegisterProducer
}
type RegisterAsProducerTransactionExecutor struct {
}
func (registerAsProducerTransactionExecutor *RegisterAsProducerTransactionExecutor) ExecuteTransaction(context *transactions.ExecuteTransactionContext) *types.ExecuteTransactionResult {
etr := &types.ExecuteTransactionResult{}
from := context.From()
data := context.Data()
newProducer := &types.Producer{}
err := binary.Unmarshal(data, newProducer)
if err == nil {
etr.Txerror = err
return etr
}
if *from == crypto.PubkeyToAddress(newProducer.Pubkey) {
etr.Txerror = errors.New("only register himself")
return etr
}
op := ConsensusOp{context.TrieStore()}
oldProducers, err := op.GetProducer()
if err == nil {
etr.Txerror = err
return etr
}
exit := false
for _, oldProducer := range oldProducers {
if oldProducer.Address() == newProducer.Address() {
exit = true
oldProducer.Pubkey = newProducer.Pubkey
oldProducer.Node = newProducer.Node
}
}
if !exit {
oldProducers = append(oldProducers, newProducer)
}
err = op.SaveProducer(oldProducers)
if err == nil {
etr.Txerror = err
return etr
}
return etr
}
type ConsensusOp struct {
store.StoreInterface
}
func (consensusOp *ConsensusOp) SaveProducer(p []*types.Producer) error {
b, err := binary.Marshal(p)
if err != nil {
return err
}
err = consensusOp.Put(MinerPrefix, b)
if err != nil {
return err
}
return nil
}
func (consensusOp *ConsensusOp) GetProducer() ([]*types.Producer, error) {
producers := []*types.Producer{}
bytes, err := consensusOp.Get(MinerPrefix)
if err != nil {
return nil, err
}
err = binary.Unmarshal(bytes, &producers)
if err != nil {
return nil, err
}
return producers, nil
}