summaryrefslogtreecommitdiff
path: root/data/account/participation.go
blob: 269163c99812e6a4f63240b795006e7ac893c3a3 (plain)
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
// Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package account

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/data/transactions"
	"github.com/algorand/go-algorand/logging"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/util/db"
)

// A Participation encapsulates a set of secrets which allows a root to
// participate in consensus. All such accounts are associated with a parent root
// account via the Address (although this parent account may not be
// resident on this machine).
//
// Participations are allowed to vote on a user's behalf for some range of
// rounds. After this range, all remaining secrets are destroyed.
//
// For correctness, all Roots should have no more than one Participation
// globally active at any time. If this condition is violated, the Root may
// equivocate. (Algorand tolerates a limited fraction of misbehaving accounts.)
type Participation struct {
	Parent basics.Address

	VRF    *crypto.VRFSecrets
	Voting *crypto.OneTimeSignatureSecrets

	// The first and last rounds for which this account is valid, respectively.
	//
	// When lastValid has concluded, this set of secrets is destroyed.
	FirstValid basics.Round
	LastValid  basics.Round

	KeyDilution uint64
}

// PersistedParticipation encapsulates the static state of the participation
// for a single address at any given moment, while providing the ability
// to handle persistence and deletion of secrets.
type PersistedParticipation struct {
	Participation

	Store db.Accessor
}

// ValidInterval returns the first and last rounds for which this participation account is valid.
func (part Participation) ValidInterval() (first, last basics.Round) {
	return part.FirstValid, part.LastValid
}

// Address returns the root account under which this participation account is registered.
func (part Participation) Address() basics.Address {
	return part.Parent
}

// OverlapsInterval returns true if the partkey is valid at all within the range of rounds (inclusive)
func (part Participation) OverlapsInterval(first, last basics.Round) bool {
	if last < first {
		logging.Base().Panicf("Round interval should be ordered (first = %v, last = %v)", first, last)
	}
	if last < part.FirstValid || first > part.LastValid {
		return false
	}
	return true
}

// VRFSecrets returns the VRF secrets associated with this Participation account.
func (part Participation) VRFSecrets() *crypto.VRFSecrets {
	return part.VRF
}

// VotingSecrets returns the voting secrets associated with this Participation account.
func (part Participation) VotingSecrets() *crypto.OneTimeSignatureSecrets {
	return part.Voting
}

// VotingSigner returns the voting secrets associated with this Participation account,
// together with the KeyDilution value.
func (part Participation) VotingSigner() crypto.OneTimeSigner {
	return crypto.OneTimeSigner{
		OneTimeSignatureSecrets: part.Voting,
		OptionalKeyDilution:     part.KeyDilution,
	}
}

// GenerateRegistrationTransaction returns a transaction object for registering a Participation with its parent.
func (part Participation) GenerateRegistrationTransaction(fee basics.MicroAlgos, txnFirstValid, txnLastValid basics.Round, leaseBytes [32]byte) transactions.Transaction {
	t := transactions.Transaction{
		Type: protocol.KeyRegistrationTx,
		Header: transactions.Header{
			Sender:     part.Parent,
			Fee:        fee,
			FirstValid: txnFirstValid,
			LastValid:  txnLastValid,
			Lease:      leaseBytes,
		},
		KeyregTxnFields: transactions.KeyregTxnFields{
			VotePK:      part.Voting.OneTimeSignatureVerifier,
			SelectionPK: part.VRF.PK,
		},
	}
	t.KeyregTxnFields.VoteFirst = part.FirstValid
	t.KeyregTxnFields.VoteLast = part.LastValid
	t.KeyregTxnFields.VoteKeyDilution = part.KeyDilution
	return t
}

// DeleteOldKeys securely deletes ephemeral keys for rounds strictly older than the given round.
func (part PersistedParticipation) DeleteOldKeys(current basics.Round, proto config.ConsensusParams) <-chan error {
	keyDilution := part.KeyDilution
	if keyDilution == 0 {
		keyDilution = proto.DefaultKeyDilution
	}

	part.Voting.DeleteBeforeFineGrained(basics.OneTimeIDForRound(current, keyDilution), keyDilution)

	errorCh := make(chan error, 1)
	deleteOldKeys := func(encodedVotingSecrets []byte) {
		errorCh <- part.Store.Atomic(func(ctx context.Context, tx *sql.Tx) error {
			_, err := tx.Exec("UPDATE ParticipationAccount SET voting=?", encodedVotingSecrets)
			if err != nil {
				return fmt.Errorf("Participation.DeleteOldKeys: failed to update account: %v", err)
			}
			return nil
		})
		close(errorCh)
	}
	voting := part.Voting.Snapshot()
	encodedVotingSecrets := protocol.Encode(&voting)
	go deleteOldKeys(encodedVotingSecrets)
	return errorCh
}

// PersistNewParent writes a new parent address to the partkey database.
func (part PersistedParticipation) PersistNewParent() error {
	return part.Store.Atomic(func(ctx context.Context, tx *sql.Tx) error {
		_, err := tx.Exec("UPDATE ParticipationAccount SET parent=?", part.Parent[:])
		return err
	})
}

// FillDBWithParticipationKeys initializes the passed database with participation keys
func FillDBWithParticipationKeys(store db.Accessor, address basics.Address, firstValid, lastValid basics.Round, keyDilution uint64) (part PersistedParticipation, err error) {
	if lastValid < firstValid {
		err = fmt.Errorf("FillDBWithParticipationKeys: lastValid %d is after firstValid %d", lastValid, firstValid)
		return
	}

	// Compute how many distinct participation keys we should generate
	firstID := basics.OneTimeIDForRound(firstValid, keyDilution)
	lastID := basics.OneTimeIDForRound(lastValid, keyDilution)
	numBatches := lastID.Batch - firstID.Batch + 1

	// Generate them
	v := crypto.GenerateOneTimeSignatureSecrets(firstID.Batch, numBatches)

	// Also generate a new VRF key, which lives in the participation keys db
	vrf := crypto.GenerateVRFSecrets()

	// Construct the Participation containing these keys to be persisted
	part = PersistedParticipation{
		Participation: Participation{
			Parent:      address,
			VRF:         vrf,
			Voting:      v,
			FirstValid:  firstValid,
			LastValid:   lastValid,
			KeyDilution: keyDilution,
		},
		Store: store,
	}
	// Persist the Participation into the database
	err = part.Persist()
	return part, err
}

// Persist writes a Participation out to a database on the disk
func (part PersistedParticipation) Persist() error {
	rawVRF := protocol.Encode(part.VRF)
	voting := part.Voting.Snapshot()
	rawVoting := protocol.Encode(&voting)

	err := part.Store.Atomic(func(ctx context.Context, tx *sql.Tx) error {
		err := partInstallDatabase(tx)
		if err != nil {
			return fmt.Errorf("failed to install database: %w", err)
		}

		_, err = tx.Exec("INSERT INTO ParticipationAccount (parent, vrf, voting, firstValid, lastValid, keyDilution) VALUES (?, ?, ?, ?, ?, ?)",
			part.Parent[:], rawVRF, rawVoting, part.FirstValid, part.LastValid, part.KeyDilution)
		if err != nil {
			return fmt.Errorf("failed to insert account: %w", err)
		}
		return nil
	})

	if err != nil {
		err = fmt.Errorf("PersistedParticipation.Persist: %w", err)
	}
	return err
}

// Migrate is called when loading participation keys.
// Calls through to the migration helper and returns the result.
func Migrate(partDB db.Accessor) error {
	return partDB.Atomic(func(ctx context.Context, tx *sql.Tx) error {
		return partMigrate(tx)
	})
}

// Close closes the underlying database handle.
func (part PersistedParticipation) Close() {
	part.Store.Close()
}