forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.go
1452 lines (1256 loc) · 51.8 KB
/
node.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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019-2023 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 node is the Algorand node itself, with functions exposed to the frontend
package node
import (
"context"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/algorand/go-algorand/agreement"
"github.com/algorand/go-algorand/agreement/gossip"
"github.com/algorand/go-algorand/catchup"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data"
"github.com/algorand/go-algorand/data/account"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/data/committee"
"github.com/algorand/go-algorand/data/pools"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/data/transactions/verify"
"github.com/algorand/go-algorand/ledger"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/ledger/simulation"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/network"
"github.com/algorand/go-algorand/network/messagetracer"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/rpcs"
"github.com/algorand/go-algorand/stateproof"
"github.com/algorand/go-algorand/util/db"
"github.com/algorand/go-algorand/util/execpool"
"github.com/algorand/go-algorand/util/metrics"
"github.com/algorand/go-algorand/util/timers"
"github.com/algorand/go-deadlock"
)
const (
participationRegistryFlushMaxWaitDuration = 30 * time.Second
)
const (
bitMismatchingVotingKey = 1 << iota
bitMismatchingSelectionKey
bitAccountOffline
bitAccountIsClosed
)
// StatusReport represents the current basic status of the node
type StatusReport struct {
LastRound basics.Round
LastVersion protocol.ConsensusVersion
NextVersion protocol.ConsensusVersion
NextVersionRound basics.Round
NextVersionSupported bool
LastRoundTimestamp time.Time
SynchronizingTime time.Duration
CatchupTime time.Duration
HasSyncedSinceStartup bool
StoppedAtUnsupportedRound bool
LastCatchpoint string // the last catchpoint hit by the node. This would get updated regardless of whether the node is catching up using catchpoints or not.
Catchpoint string // the catchpoint where we're currently catching up to. If the node isn't in fast catchup mode, it will be empty.
CatchpointCatchupTotalAccounts uint64
CatchpointCatchupProcessedAccounts uint64
CatchpointCatchupVerifiedAccounts uint64
CatchpointCatchupTotalKVs uint64
CatchpointCatchupProcessedKVs uint64
CatchpointCatchupVerifiedKVs uint64
CatchpointCatchupTotalBlocks uint64
CatchpointCatchupAcquiredBlocks uint64
UpgradePropose protocol.ConsensusVersion
UpgradeApprove bool
UpgradeDelay uint64
NextProtocolVoteBefore basics.Round
NextProtocolApprovals uint64
}
// TimeSinceLastRound returns the time since the last block was approved (locally), or 0 if no blocks seen
func (status StatusReport) TimeSinceLastRound() time.Duration {
if status.LastRoundTimestamp.IsZero() {
return time.Duration(0)
}
return time.Since(status.LastRoundTimestamp)
}
// AlgorandFullNode specifies and implements a full Algorand node.
type AlgorandFullNode struct {
mu deadlock.Mutex
ctx context.Context
cancelCtx context.CancelFunc
config config.Local
ledger *data.Ledger
net network.GossipNode
transactionPool *pools.TransactionPool
txHandler *data.TxHandler
accountManager *data.AccountManager
agreementService *agreement.Service
catchupService *catchup.Service
catchpointCatchupService *catchup.CatchpointCatchupService
blockService *rpcs.BlockService
ledgerService *rpcs.LedgerService
txPoolSyncerService *rpcs.TxSyncer
genesisDirs config.ResolvedGenesisDirs
genesisID string
genesisHash crypto.Digest
devMode bool // is this node operating in a developer mode ? ( benign agreement, broadcasting transaction generates a new block )
timestampOffset *int64
log logging.Logger
// syncStatusMu used for locking lastRoundTimestamp and hasSyncedSinceStartup
// syncStatusMu added so OnNewBlock wouldn't be blocked by oldKeyDeletionThread during catchup
syncStatusMu deadlock.Mutex
lastRoundTimestamp time.Time
hasSyncedSinceStartup bool
cryptoPool execpool.ExecutionPool
lowPriorityCryptoVerificationPool execpool.BacklogPool
highPriorityCryptoVerificationPool execpool.BacklogPool
catchupBlockAuth blockAuthenticatorImpl
oldKeyDeletionNotify chan struct{}
monitoringRoutinesWaitGroup sync.WaitGroup
tracer messagetracer.MessageTracer
stateProofWorker *stateproof.Worker
}
// TxnWithStatus represents information about a single transaction,
// in particular, whether it has appeared in some block yet or not,
// and whether it was kicked out of the txpool due to some error.
type TxnWithStatus struct {
Txn transactions.SignedTxn
// Zero indicates no confirmation
ConfirmedRound basics.Round
// PoolError indicates that the transaction was kicked out of this
// node's transaction pool (and specifies why that happened). An
// empty string indicates the transaction wasn't kicked out of this
// node's txpool due to an error.
PoolError string
// ApplyData is the transaction.ApplyData, if committed.
ApplyData transactions.ApplyData
}
// MakeFull sets up an Algorand full node
// (i.e., it returns a node that participates in consensus)
func MakeFull(log logging.Logger, rootDir string, cfg config.Local, phonebookAddresses []string, genesis bookkeeping.Genesis) (*AlgorandFullNode, error) {
node := new(AlgorandFullNode)
node.log = log.With("name", cfg.NetAddress)
node.genesisID = genesis.ID()
node.genesisHash = genesis.Hash()
node.devMode = genesis.DevMode
node.config = cfg
var err error
node.genesisDirs, err = cfg.EnsureAndResolveGenesisDirs(rootDir, genesis.ID())
if err != nil {
return nil, err
}
genalloc, err := genesis.Balances()
if err != nil {
log.Errorf("Cannot load genesis allocation: %v", err)
return nil, err
}
// tie network, block fetcher, and agreement services together
var p2pNode network.GossipNode
if cfg.EnableP2P {
// TODO: pass more appropriate genesisDir (hot/cold). Presently this is just used to store a peerID key.
p2pNode, err = network.NewP2PNetwork(node.log, node.config, node.genesisDirs.RootGenesisDir, phonebookAddresses, genesis.ID(), genesis.Network)
if err != nil {
log.Errorf("could not create p2p node: %v", err)
return nil, err
}
} else {
var wsNode *network.WebsocketNetwork
wsNode, err = network.NewWebsocketNetwork(node.log, node.config, phonebookAddresses, genesis.ID(), genesis.Network, node)
if err != nil {
log.Errorf("could not create websocket node: %v", err)
return nil, err
}
wsNode.SetPrioScheme(node)
p2pNode = wsNode
}
node.net = p2pNode
node.cryptoPool = execpool.MakePool(node)
node.lowPriorityCryptoVerificationPool = execpool.MakeBacklog(node.cryptoPool, 2*node.cryptoPool.GetParallelism(), execpool.LowPriority, node)
node.highPriorityCryptoVerificationPool = execpool.MakeBacklog(node.cryptoPool, 2*node.cryptoPool.GetParallelism(), execpool.HighPriority, node)
ledgerPaths := ledger.DirsAndPrefix{
DBFilePrefix: config.LedgerFilenamePrefix,
ResolvedGenesisDirs: node.genesisDirs,
}
node.ledger, err = data.LoadLedger(node.log, ledgerPaths, false, genesis.Proto, genalloc, node.genesisID, node.genesisHash, []ledgercore.BlockListener{}, cfg)
if err != nil {
log.Errorf("Cannot initialize ledger (%v): %v", ledgerPaths, err)
return nil, err
}
node.transactionPool = pools.MakeTransactionPool(node.ledger.Ledger, cfg, node.log)
blockListeners := []ledgercore.BlockListener{
node.transactionPool,
node,
}
node.ledger.RegisterBlockListeners(blockListeners)
txHandlerOpts := data.TxHandlerOpts{
TxPool: node.transactionPool,
ExecutionPool: node.lowPriorityCryptoVerificationPool,
Ledger: node.ledger,
Net: node.net,
GenesisID: node.genesisID,
GenesisHash: node.genesisHash,
Config: cfg,
}
node.txHandler, err = data.MakeTxHandler(txHandlerOpts)
if err != nil {
log.Errorf("Cannot initialize TxHandler: %v", err)
return nil, err
}
node.blockService = rpcs.MakeBlockService(node.log, cfg, node.ledger, p2pNode, node.genesisID)
node.ledgerService = rpcs.MakeLedgerService(cfg, node.ledger, p2pNode, node.genesisID)
rpcs.RegisterTxService(node.transactionPool, p2pNode, node.genesisID, cfg.TxPoolSize, cfg.TxSyncServeResponseSize)
// crash data is stored in the cold data directory unless otherwise specified
crashPathname := filepath.Join(node.genesisDirs.CrashGenesisDir, config.CrashFilename)
crashAccess, err := db.MakeAccessor(crashPathname, false, false)
if err != nil {
log.Errorf("Cannot load crash data: %v", err)
return nil, err
}
blockValidator := blockValidatorImpl{l: node.ledger, verificationPool: node.highPriorityCryptoVerificationPool}
agreementLedger := makeAgreementLedger(node.ledger, node.net)
var agreementClock timers.Clock[agreement.TimeoutType]
if node.devMode {
agreementClock = timers.MakeFrozenClock[agreement.TimeoutType]()
} else {
agreementClock = timers.MakeMonotonicClock[agreement.TimeoutType](time.Now())
}
agreementParameters := agreement.Parameters{
Logger: log,
Accessor: crashAccess,
Clock: agreementClock,
Local: node.config,
Network: gossip.WrapNetwork(node.net, log, cfg),
Ledger: agreementLedger,
BlockFactory: node,
BlockValidator: blockValidator,
KeyManager: node,
RandomSource: node,
BacklogPool: node.highPriorityCryptoVerificationPool,
}
node.agreementService, err = agreement.MakeService(agreementParameters)
if err != nil {
log.Errorf("unable to initialize agreement: %v", err)
return nil, err
}
node.catchupBlockAuth = blockAuthenticatorImpl{Ledger: node.ledger, AsyncVoteVerifier: agreement.MakeAsyncVoteVerifier(node.lowPriorityCryptoVerificationPool)}
node.catchupService = catchup.MakeService(node.log, node.config, p2pNode, node.ledger, node.catchupBlockAuth, agreementLedger.UnmatchedPendingCertificates, node.lowPriorityCryptoVerificationPool)
node.txPoolSyncerService = rpcs.MakeTxSyncer(node.transactionPool, node.net, node.txHandler.SolicitedTxHandler(), time.Duration(cfg.TxSyncIntervalSeconds)*time.Second, time.Duration(cfg.TxSyncTimeoutSeconds)*time.Second, cfg.TxSyncServeResponseSize)
registry, err := ensureParticipationDB(node.genesisDirs.ColdGenesisDir, node.log)
if err != nil {
log.Errorf("unable to initialize the participation registry database: %v", err)
return nil, err
}
node.accountManager = data.MakeAccountManager(log, registry)
err = node.loadParticipationKeys()
if err != nil {
log.Errorf("Cannot load participation keys: %v", err)
return nil, err
}
node.oldKeyDeletionNotify = make(chan struct{}, 1)
catchpointCatchupState, err := node.ledger.GetCatchpointCatchupState(context.Background())
if err != nil {
log.Errorf("unable to determine catchpoint catchup state: %v", err)
return nil, err
}
if catchpointCatchupState != ledger.CatchpointCatchupStateInactive {
accessor := ledger.MakeCatchpointCatchupAccessor(node.ledger.Ledger, node.log)
node.catchpointCatchupService, err = catchup.MakeResumedCatchpointCatchupService(context.Background(), node, node.log, node.net, accessor, node.config)
if err != nil {
log.Errorf("unable to create catchpoint catchup service: %v", err)
return nil, err
}
node.log.Infof("resuming catchpoint catchup from state %d", catchpointCatchupState)
}
node.tracer = messagetracer.NewTracer(log).Init(cfg)
gossip.SetTrace(agreementParameters.Network, node.tracer)
node.stateProofWorker = stateproof.NewWorker(node.genesisDirs.StateproofGenesisDir, node.log, node.accountManager, node.ledger.Ledger, node.net, node)
return node, err
}
// Config returns a copy of the node's Local configuration
func (node *AlgorandFullNode) Config() config.Local {
return node.config
}
// Start the node: connect to peers and run the agreement service while obtaining a lock. Doesn't wait for initial sync.
func (node *AlgorandFullNode) Start() {
node.mu.Lock()
defer node.mu.Unlock()
// Set up a context we can use to cancel goroutines on Stop()
node.ctx, node.cancelCtx = context.WithCancel(context.Background())
// The start network is being called only after the various services start up.
// We want to do so in order to let the services register their callbacks with the
// network package before any connections are being made.
startNetwork := func() {
if !node.config.DisableNetworking {
// start accepting connections
node.net.Start()
node.config.NetAddress, _ = node.net.Address()
}
}
if node.catchpointCatchupService != nil {
startNetwork()
node.catchpointCatchupService.Start(node.ctx)
} else {
node.catchupService.Start()
node.agreementService.Start()
node.txPoolSyncerService.Start(node.catchupService.InitialSyncDone)
node.blockService.Start()
node.ledgerService.Start()
node.txHandler.Start()
node.stateProofWorker.Start()
startNetwork()
node.startMonitoringRoutines()
}
}
// startMonitoringRoutines starts the internal monitoring routines used by the node.
func (node *AlgorandFullNode) startMonitoringRoutines() {
node.monitoringRoutinesWaitGroup.Add(2)
go node.txPoolGaugeThread(node.ctx.Done())
// Delete old participation keys
go node.oldKeyDeletionThread(node.ctx.Done())
if node.config.EnableUsageLog {
node.monitoringRoutinesWaitGroup.Add(1)
go logging.UsageLogThread(node.ctx, node.log, 100*time.Millisecond, &node.monitoringRoutinesWaitGroup)
}
}
// waitMonitoringRoutines waits for all the monitoring routines to exit. Note that
// the node.mu must not be taken, and that the node's context should have been canceled.
func (node *AlgorandFullNode) waitMonitoringRoutines() {
node.monitoringRoutinesWaitGroup.Wait()
}
// ListeningAddress retrieves the node's current listening address, if any.
// Returns true if currently listening, false otherwise.
func (node *AlgorandFullNode) ListeningAddress() (string, bool) {
node.mu.Lock()
defer node.mu.Unlock()
return node.net.Address()
}
// Stop stops running the node. Once a node is closed, it can never start again.
func (node *AlgorandFullNode) Stop() {
node.mu.Lock()
defer func() {
node.mu.Unlock()
node.waitMonitoringRoutines()
}()
node.net.ClearHandlers()
if !node.config.DisableNetworking {
node.net.Stop()
}
if node.catchpointCatchupService != nil {
node.catchpointCatchupService.Stop()
} else {
node.stateProofWorker.Stop()
node.txHandler.Stop()
node.agreementService.Shutdown()
node.catchupService.Stop()
node.txPoolSyncerService.Stop()
node.blockService.Stop()
node.ledgerService.Stop()
}
node.catchupBlockAuth.Quit()
node.highPriorityCryptoVerificationPool.Shutdown()
node.lowPriorityCryptoVerificationPool.Shutdown()
node.cryptoPool.Shutdown()
node.cancelCtx()
}
// note: unlike the other two functions, this accepts a whole filename
func (node *AlgorandFullNode) getExistingPartHandle(filename string) (db.Accessor, error) {
filename = filepath.Join(node.genesisDirs.RootGenesisDir, filename)
_, err := os.Stat(filename)
if err == nil {
return db.MakeErasableAccessor(filename)
}
return db.Accessor{}, err
}
// Ledger exposes the node's ledger handle to the algod API code
func (node *AlgorandFullNode) Ledger() *data.Ledger {
return node.ledger
}
// writeDevmodeBlock generates a new block for a devmode, and write it to the ledger.
func (node *AlgorandFullNode) writeDevmodeBlock() (err error) {
var vb *ledgercore.ValidatedBlock
vb, err = node.transactionPool.AssembleDevModeBlock()
if err != nil || vb == nil {
return
}
// Make a new validated block.
prevRound := vb.Block().Round() - 1
prev, err := node.ledger.BlockHdr(prevRound)
if err != nil {
return err
}
blk := vb.Block()
// Set block timestamp based on offset, if set.
// Make sure block timestamp is not greater than MaxInt64.
if node.timestampOffset != nil && *node.timestampOffset < math.MaxInt64-prev.TimeStamp {
blk.TimeStamp = prev.TimeStamp + *node.timestampOffset
}
blk.BlockHeader.Seed = committee.Seed(prev.Hash())
vb2 := ledgercore.MakeValidatedBlock(blk, vb.Delta())
vb = &vb2
// add the newly generated block to the ledger
err = node.ledger.AddValidatedBlock(*vb, agreement.Certificate{Round: vb.Block().Round()})
return err
}
// BroadcastSignedTxGroup broadcasts a transaction group that has already been signed.
func (node *AlgorandFullNode) BroadcastSignedTxGroup(txgroup []transactions.SignedTxn) (err error) {
// in developer mode, we need to take a lock, so that each new transaction group would truly
// render into a unique block.
if node.devMode {
node.mu.Lock()
defer func() {
// if we added the transaction successfully to the transaction pool, then
// attempt to generate a block and write it to the ledger.
if err == nil {
err = node.writeDevmodeBlock()
}
node.mu.Unlock()
}()
}
return node.broadcastSignedTxGroup(txgroup)
}
// AsyncBroadcastSignedTxGroup feeds a raw transaction group directly to the transaction pool.
// This method is intended to be used for performance testing and debugging purposes only.
func (node *AlgorandFullNode) AsyncBroadcastSignedTxGroup(txgroup []transactions.SignedTxn) (err error) {
return node.txHandler.LocalTransaction(txgroup)
}
// BroadcastInternalSignedTxGroup broadcasts a transaction group that has already been signed.
// It is originated internally, and in DevMode, it will not advance the round.
func (node *AlgorandFullNode) BroadcastInternalSignedTxGroup(txgroup []transactions.SignedTxn) (err error) {
return node.broadcastSignedTxGroup(txgroup)
}
var broadcastTxSucceeded = metrics.MakeCounter(metrics.BroadcastSignedTxGroupSucceeded)
var broadcastTxFailed = metrics.MakeCounter(metrics.BroadcastSignedTxGroupFailed)
// broadcastSignedTxGroup broadcasts a transaction group that has already been signed.
func (node *AlgorandFullNode) broadcastSignedTxGroup(txgroup []transactions.SignedTxn) (err error) {
defer func() {
if err != nil {
broadcastTxFailed.Inc(nil)
} else {
broadcastTxSucceeded.Inc(nil)
}
}()
lastRound := node.ledger.Latest()
var b bookkeeping.BlockHeader
b, err = node.ledger.BlockHdr(lastRound)
if err != nil {
node.log.Errorf("could not get block header from last round %v: %v", lastRound, err)
return err
}
_, err = verify.TxnGroup(txgroup, &b, node.ledger.VerifiedTransactionCache(), node.ledger)
if err != nil {
node.log.Warnf("malformed transaction: %v", err)
return err
}
err = node.transactionPool.Remember(txgroup)
if err != nil {
node.log.Infof("rejected by local pool: %v - transaction group was %+v", err, txgroup)
return err
}
err = node.ledger.VerifiedTransactionCache().Pin(txgroup)
if err != nil {
logging.Base().Infof("unable to pin transaction: %v", err)
}
// DevMode nodes do not broadcast txns to the network
if node.devMode {
return nil
}
var enc []byte
var txids []transactions.Txid
for _, tx := range txgroup {
enc = append(enc, protocol.Encode(&tx)...)
txids = append(txids, tx.ID())
}
err = node.net.Broadcast(context.TODO(), protocol.TxnTag, enc, false, nil)
if err != nil {
node.log.Infof("failure broadcasting transaction to network: %v - transaction group was %+v", err, txgroup)
return err
}
node.log.Infof("Sent signed tx group with IDs %v", txids)
return nil
}
// Simulate speculatively runs a transaction group against the current
// blockchain state and returns the effects and/or errors that would result.
func (node *AlgorandFullNode) Simulate(request simulation.Request) (result simulation.Result, err error) {
simulator := simulation.MakeSimulator(node.ledger, node.config.EnableDeveloperAPI)
return simulator.Simulate(request)
}
// ListTxns returns SignedTxns associated with a specific account in a range of Rounds (inclusive).
// TxnWithStatus returns the round in which a particular transaction appeared,
// since that information is not part of the SignedTxn itself.
func (node *AlgorandFullNode) ListTxns(addr basics.Address, minRound basics.Round, maxRound basics.Round) ([]TxnWithStatus, error) {
result := make([]TxnWithStatus, 0)
for r := minRound; r <= maxRound; r++ {
h, err := node.ledger.AddressTxns(addr, r)
if err != nil {
return nil, err
}
for _, tx := range h {
result = append(result, TxnWithStatus{
Txn: tx.SignedTxn,
ConfirmedRound: r,
ApplyData: tx.ApplyData,
})
}
}
return result, nil
}
// GetTransaction looks for the required txID within with a specific account within a range of rounds (inclusive) and
// returns the SignedTxn and true iff it finds the transaction.
func (node *AlgorandFullNode) GetTransaction(addr basics.Address, txID transactions.Txid, minRound basics.Round, maxRound basics.Round) (TxnWithStatus, bool) {
// start with the most recent round, and work backwards:
// this will abort early if it hits pruned rounds
if maxRound < minRound {
return TxnWithStatus{}, false
}
r := maxRound
for {
h, err := node.ledger.AddressTxns(addr, r)
if err != nil {
return TxnWithStatus{}, false
}
for _, tx := range h {
if tx.ID() == txID {
return TxnWithStatus{
Txn: tx.SignedTxn,
ConfirmedRound: r,
ApplyData: tx.ApplyData,
}, true
}
}
if r == minRound {
break
}
r--
}
return TxnWithStatus{}, false
}
// GetPendingTransaction looks for the required txID in the recent ledger
// blocks, in the txpool, and in the txpool's status cache. It returns
// the SignedTxn (with status information), and a bool to indicate if the
// transaction was found.
func (node *AlgorandFullNode) GetPendingTransaction(txID transactions.Txid) (res TxnWithStatus, found bool) {
// We need to check both the pool and the ledger's blocks.
// If the transaction is found in a committed block, that
// takes precedence. But we check the pool first, because
// otherwise there could be a race between the pool and the
// ledger, where the block wasn't in the ledger at first,
// but by the time we check the pool, it's not there either
// because it committed.
// The default return value is found=false, which is
// appropriate if the transaction isn't found anywhere.
// Check if it's in the pool or evicted from the pool.
tx, txErr, found := node.transactionPool.Lookup(txID)
if found {
res = TxnWithStatus{
Txn: tx,
ConfirmedRound: 0,
PoolError: txErr,
}
found = true
// Keep looking in the ledger.
}
var maxLife basics.Round
latest := node.ledger.Latest()
proto, err := node.ledger.ConsensusParams(latest)
if err == nil {
maxLife = basics.Round(proto.MaxTxnLife)
} else {
node.log.Errorf("node.GetPendingTransaction: cannot get consensus params for latest round %v", latest)
}
// Search from newest to oldest round up to the max life of a transaction.
maxRound := latest
minRound := maxRound.SubSaturate(maxLife)
// Since we're using uint64, if the minRound is 0, we need to check for an underflow.
if minRound == 0 {
minRound++
}
// If we did find the transaction, we know there is no point
// checking rounds earlier or later than validity rounds
if found {
if tx.Txn.FirstValid > minRound {
minRound = tx.Txn.FirstValid
}
if tx.Txn.LastValid < maxRound {
maxRound = tx.Txn.LastValid
}
}
for r := maxRound; r >= minRound; r-- {
tx, found, err := node.ledger.LookupTxid(txID, r)
if err != nil || !found {
continue
}
return TxnWithStatus{
Txn: tx.SignedTxn,
ConfirmedRound: r,
ApplyData: tx.ApplyData,
}, true
}
// Return whatever we found in the pool (if anything).
return
}
// Status returns a StatusReport structure reporting our status as Active and with our ledger's LastRound
func (node *AlgorandFullNode) Status() (StatusReport, error) {
node.syncStatusMu.Lock()
lastRoundTimestamp := node.lastRoundTimestamp
hasSyncedSinceStartup := node.hasSyncedSinceStartup
node.syncStatusMu.Unlock()
node.mu.Lock()
defer node.mu.Unlock()
var s StatusReport
var err error
if node.catchpointCatchupService != nil {
s = catchpointCatchupStatus(node.catchpointCatchupService.GetLatestBlockHeader(), node.catchpointCatchupService.GetStatistics())
} else {
s, err = latestBlockStatus(node.ledger, node.catchupService)
}
s.LastRoundTimestamp = lastRoundTimestamp
s.HasSyncedSinceStartup = hasSyncedSinceStartup
return s, err
}
func catchpointCatchupStatus(lastBlockHeader bookkeeping.BlockHeader, stats catchup.CatchpointCatchupStats) (s StatusReport) {
// we're in catchpoint catchup mode.
s.LastRound = lastBlockHeader.Round
s.LastVersion = lastBlockHeader.CurrentProtocol
s.NextVersion, s.NextVersionRound, s.NextVersionSupported = lastBlockHeader.NextVersionInfo()
s.StoppedAtUnsupportedRound = s.LastRound+1 == s.NextVersionRound && !s.NextVersionSupported
// for now, I'm leaving this commented out. Once we refactor some of the ledger locking mechanisms, we
// should be able to make this call work.
//s.LastCatchpoint = node.ledger.GetLastCatchpointLabel()
// report back the catchpoint catchup progress statistics
s.Catchpoint = stats.CatchpointLabel
s.CatchpointCatchupTotalAccounts = stats.TotalAccounts
s.CatchpointCatchupProcessedAccounts = stats.ProcessedAccounts
s.CatchpointCatchupVerifiedAccounts = stats.VerifiedAccounts
s.CatchpointCatchupTotalKVs = stats.TotalKVs
s.CatchpointCatchupProcessedKVs = stats.ProcessedKVs
s.CatchpointCatchupVerifiedKVs = stats.VerifiedKVs
s.CatchpointCatchupTotalBlocks = stats.TotalBlocks
s.CatchpointCatchupAcquiredBlocks = stats.AcquiredBlocks
s.CatchupTime = time.Since(stats.StartTime)
return
}
func latestBlockStatus(ledger *data.Ledger, catchupService *catchup.Service) (s StatusReport, err error) {
// we're not in catchpoint catchup mode
var b bookkeeping.BlockHeader
s.LastRound = ledger.Latest()
b, err = ledger.BlockHdr(s.LastRound)
if err != nil {
return
}
s.LastVersion = b.CurrentProtocol
s.NextVersion, s.NextVersionRound, s.NextVersionSupported = b.NextVersionInfo()
s.StoppedAtUnsupportedRound = s.LastRound+1 == s.NextVersionRound && !s.NextVersionSupported
s.LastCatchpoint = ledger.GetLastCatchpointLabel()
s.SynchronizingTime = catchupService.SynchronizingTime()
s.CatchupTime = catchupService.SynchronizingTime()
s.UpgradePropose = b.UpgradeVote.UpgradePropose
s.UpgradeApprove = b.UpgradeApprove
s.UpgradeDelay = uint64(b.UpgradeVote.UpgradeDelay)
s.NextProtocolVoteBefore = b.NextProtocolVoteBefore
s.NextProtocolApprovals = b.UpgradeState.NextProtocolApprovals
return
}
// GenesisID returns the ID of the genesis node.
func (node *AlgorandFullNode) GenesisID() string {
node.mu.Lock()
defer node.mu.Unlock()
return node.genesisID
}
// GenesisHash returns the hash of the genesis configuration.
func (node *AlgorandFullNode) GenesisHash() crypto.Digest {
node.mu.Lock()
defer node.mu.Unlock()
return node.genesisHash
}
// SuggestedFee returns the suggested fee per byte recommended to ensure a new transaction is processed in a timely fashion.
// Caller should set fee to max(MinTxnFee, SuggestedFee() * len(encoded SignedTxn))
func (node *AlgorandFullNode) SuggestedFee() basics.MicroAlgos {
return basics.MicroAlgos{Raw: node.transactionPool.FeePerByte()}
}
// GetPendingTxnsFromPool returns a snapshot of every pending transactions from the node's transaction pool in a slice.
// Transactions are sorted in decreasing order. If no transactions, returns an empty slice.
func (node *AlgorandFullNode) GetPendingTxnsFromPool() ([]transactions.SignedTxn, error) {
return bookkeeping.SignedTxnGroupsFlatten(node.transactionPool.PendingTxGroups()), nil
}
// ensureParticipationDB opens or creates a participation DB.
func ensureParticipationDB(genesisDir string, log logging.Logger) (account.ParticipationRegistry, error) {
accessorFile := filepath.Join(genesisDir, config.ParticipationRegistryFilename)
accessor, err := db.OpenErasablePair(accessorFile)
if err != nil {
return nil, err
}
return account.MakeParticipationRegistry(accessor, log)
}
// ListParticipationKeys returns all participation keys currently installed on the node
func (node *AlgorandFullNode) ListParticipationKeys() (partKeys []account.ParticipationRecord, err error) {
return node.accountManager.Registry().GetAll(), nil
}
// GetParticipationKey retries the information of a participation id from the node
func (node *AlgorandFullNode) GetParticipationKey(partKeyID account.ParticipationID) (account.ParticipationRecord, error) {
rval := node.accountManager.Registry().Get(partKeyID)
if rval.IsZero() {
return account.ParticipationRecord{}, account.ErrParticipationIDNotFound
}
return rval, nil
}
// RemoveParticipationKey given a participation id, remove the records from the node
func (node *AlgorandFullNode) RemoveParticipationKey(partKeyID account.ParticipationID) error {
// Need to remove the file and then remove the entry in the registry
// Let's first get the recorded information from the registry so we can lookup the file
partRecord := node.accountManager.Registry().Get(partKeyID)
if partRecord.IsZero() {
return account.ErrParticipationIDNotFound
}
outDir := node.genesisDirs.RootGenesisDir
filename := config.PartKeyFilename(partRecord.ParticipationID.String(), uint64(partRecord.FirstValid), uint64(partRecord.LastValid))
fullyQualifiedFilename := filepath.Join(outDir, filepath.Base(filename))
err := node.accountManager.Registry().Delete(partKeyID)
if err != nil {
return err
}
err = node.accountManager.Registry().Flush(participationRegistryFlushMaxWaitDuration)
if err != nil {
return err
}
// Only after deleting and flushing do we want to remove the file
_ = os.Remove(fullyQualifiedFilename)
return nil
}
// AppendParticipationKeys given a participation id, remove the records from the node
func (node *AlgorandFullNode) AppendParticipationKeys(partKeyID account.ParticipationID, keys account.StateProofKeys) error {
err := node.accountManager.Registry().AppendKeys(partKeyID, keys)
if err != nil {
return err
}
return node.accountManager.Registry().Flush(participationRegistryFlushMaxWaitDuration)
}
func createTemporaryParticipationKey(outDir string, partKeyBinary []byte) (string, error) {
var sb strings.Builder
// Create a temporary filename with a UUID so that we can call this function twice
// in a row without worrying about collisions
sb.WriteString("tempPartKeyBinary.")
sb.WriteString(fmt.Sprintf("%d", crypto.RandUint64()))
sb.WriteString(".bin")
tempFile := filepath.Join(outDir, filepath.Base(sb.String()))
file, err := os.Create(tempFile)
if err != nil {
return "", err
}
_, err = file.Write(partKeyBinary)
file.Close()
if err != nil {
os.Remove(tempFile)
return "", err
}
return tempFile, nil
}
// InstallParticipationKey Given a participation key binary stream install the participation key.
func (node *AlgorandFullNode) InstallParticipationKey(partKeyBinary []byte) (account.ParticipationID, error) {
outDir := node.genesisDirs.RootGenesisDir
fullyQualifiedTempFile, err := createTemporaryParticipationKey(outDir, partKeyBinary)
// We need to make sure no tempfile is created/remains if there is an error
// However, we will eventually rename this file but if we fail in-between
// this point and the rename we want to ensure that we remove the temporary file
// After we rename, this will fail anyway since the file will not exist
// Explicitly ignore the error with a closure
defer func(name string) {
_ = os.Remove(name)
}(fullyQualifiedTempFile)
if err != nil {
return account.ParticipationID{}, err
}
inputdb, err := db.MakeErasableAccessor(fullyQualifiedTempFile)
if err != nil {
return account.ParticipationID{}, err
}
defer inputdb.Close()
partkey, err := account.RestoreParticipationWithSecrets(inputdb)
if err != nil {
return account.ParticipationID{}, err
}
defer partkey.Close()
if partkey.Parent == (basics.Address{}) {
return account.ParticipationID{}, fmt.Errorf("cannot install partkey with missing (zero) parent address")
}
// Tell the AccountManager about the Participation (dupes don't matter) so we ignore the return value
// This is ephemeral since we are deleting the file after this function is done
added := node.accountManager.AddParticipation(partkey, true)
if !added {
return account.ParticipationID{}, fmt.Errorf("ParticipationRegistry: cannot register duplicate participation key")
}
err = insertStateProofToRegistry(partkey, node)
if err != nil {
return account.ParticipationID{}, err
}
err = node.accountManager.Registry().Flush(participationRegistryFlushMaxWaitDuration)
if err != nil {
return account.ParticipationID{}, err
}
return partkey.ID(), nil
}
func (node *AlgorandFullNode) loadParticipationKeys() error {
// Generate a list of all potential participation key files
genesisDir := node.genesisDirs.RootGenesisDir
files, err := os.ReadDir(genesisDir)
if err != nil {
return fmt.Errorf("AlgorandFullNode.loadPartitipationKeys: could not read directory %v: %v", genesisDir, err)
}
// For each of these files
for _, info := range files {
// If it can't be a participation key database, skip it
if !config.IsPartKeyFilename(info.Name()) {
continue
}
filename := info.Name()
// Fetch a handle to this database
handle, err := node.getExistingPartHandle(filename)
if err != nil {
if db.IsErrBusy(err) {
// this is a special case:
// we might get "database is locked" when we attempt to access a database that is concurrently updating its participation keys.
// that database is clearly already on the account manager, and doesn't need to be processed through this logic, and therefore
// we can safely ignore that fail case.
continue
}
return fmt.Errorf("AlgorandFullNode.loadParticipationKeys: cannot load db %v: %v", filename, err)
}
// Fetch an account.Participation from the database
// currently, we load all stateproof secrets to memory which is not ideal .
// as part of the participation interface changes , secrets will no longer
// be loaded like this.
part, err := account.RestoreParticipationWithSecrets(handle)
if err != nil {
handle.Close()
if err == account.ErrUnsupportedSchema {
node.log.Infof("Loaded participation keys from storage: %s %s", part.Address(), info.Name())
node.log.Warnf("loadParticipationKeys: not loading unsupported participation key: %s; renaming to *.old", info.Name())
fullname := filepath.Join(genesisDir, info.Name())
renamedFileName := filepath.Join(fullname, ".old")
err = os.Rename(fullname, renamedFileName)
if err != nil {
node.log.Warnf("loadParticipationKeys: failed to rename unsupported participation key file '%s' to '%s': %v", fullname, renamedFileName, err)
}