forked from planetdecred/dcrlibwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consensus.go
273 lines (237 loc) · 8.05 KB
/
consensus.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
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
package dcrlibwallet
import (
"fmt"
"sort"
"strings"
"decred.org/dcrwallet/v2/errors"
w "decred.org/dcrwallet/v2/wallet"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/wire"
)
// AgendaStatusType defines the various agenda statuses.
type AgendaStatusType string
const (
dcrdataAgendasAPIMainnetUrl = "https://dcrdata.decred.org/api/agendas"
dcrdataAgendasAPITestnetUrl = "https://testnet.decred.org/api/agendas"
// AgendaStatusUpcoming used to define an agenda yet to vote.
AgendaStatusUpcoming AgendaStatusType = "upcoming"
// AgendaStatusInProgress used to define an agenda with voting ongoing.
AgendaStatusInProgress AgendaStatusType = "in progress"
// AgendaStatusFailed used to define an agenda when the votes tally does not
// attain the minimum threshold set. Activation height is not set for such an
// agenda.
AgendaStatusFailed AgendaStatusType = "failed"
// AgendaStatusLockedIn used to define an agenda that has passed after attaining
// the minimum set threshold.
AgendaStatusLockedIn AgendaStatusType = "locked in"
// AgendaStatusFinished used to define an agenda that has finished voting.
AgendaStatusFinished AgendaStatusType = "finished"
// UnknownStatus is used when a status string is not recognized.
UnknownStatus AgendaStatusType = "unknown"
)
func (a AgendaStatusType) String() string {
switch a {
case AgendaStatusUpcoming:
return "upcoming"
case AgendaStatusInProgress:
return "in progress"
case AgendaStatusLockedIn:
return "locked in"
case AgendaStatusFailed:
return "failed"
case AgendaStatusFinished:
return "finished"
default:
return "unknown"
}
}
// AgendaStatusFromStr creates an agenda status from a string. If "UnknownStatus"
// is returned then an invalid status string has been passed.
func AgendaStatusFromStr(status string) AgendaStatusType {
switch strings.ToLower(status) {
case "defined", "upcoming":
return AgendaStatusUpcoming
case "started", "in progress":
return AgendaStatusInProgress
case "failed":
return AgendaStatusFailed
case "lockedin", "locked in":
return AgendaStatusLockedIn
case "active", "finished":
return AgendaStatusFinished
default:
return UnknownStatus
}
}
// SetVoteChoice sets a voting choice for the specified agenda. If a ticket
// hash is provided, the voting choice is also updated with the VSP controlling
// the ticket. If a ticket hash isn't provided, the vote choice is saved to the
// local wallet database and the VSPs controlling all unspent, unexpired tickets
// are updated to use the specified vote choice.
func (wallet *Wallet) SetVoteChoice(agendaID, choiceID, hash string, passphrase []byte) error {
var ticketHash *chainhash.Hash
if hash != "" {
hash, err := chainhash.NewHashFromStr(hash)
if err != nil {
return fmt.Errorf("inavlid hash: %w", err)
}
ticketHash = hash
}
// The wallet will need to be unlocked to sign the API
// request(s) for setting this vote choice with the VSP.
err := wallet.UnlockWallet(passphrase)
if err != nil {
return translateError(err)
}
defer wallet.LockWallet()
ctx := wallet.shutdownContext()
// get choices
choices, _, err := wallet.Internal().AgendaChoices(ctx, ticketHash) // returns saved prefs for current agendas
if err != nil {
return err
}
currentChoice := w.AgendaChoice{
AgendaID: agendaID,
ChoiceID: "abstain", // default to abstain as current choice if not found in wallet
}
for i := range choices {
if choices[i].AgendaID == agendaID {
currentChoice.ChoiceID = choices[i].ChoiceID
break
}
}
newChoice := w.AgendaChoice{
AgendaID: agendaID,
ChoiceID: choiceID,
}
_, err = wallet.Internal().SetAgendaChoices(ctx, ticketHash, newChoice)
if err != nil {
return err
}
var vspPreferenceUpdateSuccess bool
defer func() {
if !vspPreferenceUpdateSuccess {
// Updating the agenda voting preference with the vsp failed,
// revert the locally saved voting preference for the agenda.
_, revertError := wallet.Internal().SetAgendaChoices(ctx, ticketHash, currentChoice)
if revertError != nil {
log.Errorf("unable to revert locally saved voting preference: %v", revertError)
}
}
}()
// If a ticket hash is provided, set the specified vote choice with
// the VSP associated with the provided ticket. Otherwise, set the
// vote choice with the VSPs associated with all "votable" tickets.
ticketHashes := make([]*chainhash.Hash, 0)
if ticketHash != nil {
ticketHashes = append(ticketHashes, ticketHash)
} else {
err = wallet.Internal().ForUnspentUnexpiredTickets(ctx, func(hash *chainhash.Hash) error {
ticketHashes = append(ticketHashes, hash)
return nil
})
if err != nil {
return fmt.Errorf("unable to fetch hashes for all unspent, unexpired tickets: %v", err)
}
}
// Never return errors from this for loop, so all tickets are tried.
// The first error will be returned to the caller.
var firstErr error
for _, tHash := range ticketHashes {
vspTicketInfo, err := wallet.Internal().VSPTicketInfo(ctx, tHash)
if err != nil {
// Ignore NotExist error, just means the ticket is not
// registered with a VSP, nothing more to do here.
if firstErr == nil && !errors.Is(err, errors.NotExist) {
firstErr = err
}
continue // try next tHash
}
// Update the vote choice for the ticket with the associated VSP.
vspClient, err := wallet.VSPClient(vspTicketInfo.Host, vspTicketInfo.PubKey)
if err != nil && firstErr == nil {
firstErr = err
continue // try next tHash
}
err = vspClient.SetVoteChoice(ctx, tHash, []w.AgendaChoice{newChoice}, nil, nil)
if err != nil && firstErr == nil {
firstErr = err
continue // try next tHash
}
}
vspPreferenceUpdateSuccess = firstErr == nil
return firstErr
}
// AllVoteAgendas returns all agendas of all stake versions for the active
// network and this version of the software. Also returns any saved vote
// preferences for the agendas of the current stake version. Vote preferences
// for older agendas cannot currently be retrieved.
func (wallet *Wallet) AllVoteAgendas(hash string, newestFirst bool) ([]*Agenda, error) {
if wallet.chainParams.Deployments == nil {
return nil, nil // no agendas to return
}
var ticketHash *chainhash.Hash
if hash != "" {
hash, err := chainhash.NewHashFromStr(hash)
if err != nil {
return nil, fmt.Errorf("inavlid hash: %w", err)
}
ticketHash = hash
}
ctx := wallet.shutdownContext()
choices, _, err := wallet.Internal().AgendaChoices(ctx, ticketHash) // returns saved prefs for current agendas
if err != nil {
return nil, err
}
// Check for all agendas from the intital stake version to the
// current stake version, in order to fetch legacy agendas.
deployments := make([]chaincfg.ConsensusDeployment, 0)
var i uint32
for i = 1; i <= voteVersion(wallet.chainParams); i++ {
deployments = append(deployments, wallet.chainParams.Deployments[i]...)
}
// Fetch high level agenda detail form dcrdata api.
var dcrdataAgenda []DcrdataAgenda
host := dcrdataAgendasAPIMainnetUrl
if wallet.chainParams.Net == wire.TestNet3 {
host = dcrdataAgendasAPITestnetUrl
}
_, _, err = HttpGet(host, &dcrdataAgenda)
if err != nil {
return nil, err
}
agendas := make([]*Agenda, len(deployments))
var status string
for i := range deployments {
d := &deployments[i]
votingPreference := "abstain" // assume abstain, if we have the saved pref, it'll be updated below
for c := range choices {
if choices[c].AgendaID == d.Vote.Id {
votingPreference = choices[c].ChoiceID
break
}
}
for j := range dcrdataAgenda {
if dcrdataAgenda[j].Name == d.Vote.Id {
status = AgendaStatusFromStr(dcrdataAgenda[j].Status).String()
}
}
agendas[i] = &Agenda{
AgendaID: d.Vote.Id,
Description: d.Vote.Description,
Mask: uint32(d.Vote.Mask),
Choices: d.Vote.Choices,
VotingPreference: votingPreference,
StartTime: int64(d.StartTime),
ExpireTime: int64(d.ExpireTime),
Status: status,
}
}
if newestFirst {
sort.Slice(agendas, func(i, j int) bool {
return agendas[i].StartTime > agendas[j].StartTime
})
}
return agendas, nil
}