Compare commits

...

779 Commits

Author SHA1 Message Date
Raul Jordan
6af950f001 Add Back Displaying Deposit Data + Misc Bugs (#6856)
* show deposit data tx
* display
* improve logic for derived
* further improve experience
* imports
* gaz
2020-08-03 20:17:34 +00:00
Raul Jordan
700d82236b Fix Critical Account Keystores Bugs (#6854)
* no need for pass in new account create
* disallow duplicates
* deduplicate and test
* gaz
* fix up broken tests
* unit test for no duplicates
* Merge branch 'master' into fix-account-create
* fix import
* Merge refs/heads/master into fix-account-create
* Merge branch 'fix-account-create' of github.com:prysmaticlabs/prysm into fix-account-create
2020-08-03 18:58:04 +00:00
terence tsao
ee7da0d451 ForceCheckpoint return early when zero hashes (#6852)
* Setter: return early with zero hashes
* Test: zero hashes don't panic
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge refs/heads/master into zero-hashes
* Merge refs/heads/master into zero-hashes
* Merge refs/heads/master into zero-hashes
2020-08-03 18:34:54 +00:00
Nishant Das
69e0e302b3 Use Less Intensive Search (#6848)
* use less intensive search
* Add mock method to implement Listener
* Merge refs/heads/master into lessIntensiveSearch
* Merge refs/heads/master into lessIntensiveSearch
2020-08-03 18:10:23 +00:00
terence tsao
d06dcd2eec Update DepositContractFlag default to Medalla (#6853)
* Update medalla deposit contract address
2020-08-03 17:40:05 +00:00
Raul Jordan
593d3daf84 Better Password Input Experience (#6849)
* more sane passwords
2020-08-03 17:05:30 +00:00
Shay Zluf
6582014b80 Fix deposit data copy (#6847)
* fix deposit data copy

* goimports
2020-08-03 16:25:19 +03:00
Nishant Das
e5dde1c6ef fix enrs (#6846) 2020-08-03 20:05:36 +08:00
terence tsao
d3a9b47643 Update medalla bootnodes (#6836)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-08-02 18:05:08 -05:00
Ivan Martinez
7903ec0b12 Fix CMD Config and modify --historical-slasher-node (#6730)
* Fix CMD config overwriting
* Rename and change historical slasher node
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-cmd-config
* Fix
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Add storage warning
* Merge branch 'fix-cmd-config' of github.com:prysmaticlabs/prysm into fix-cmd-config
* Remove period
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Add default values test
* Merge branch 'fix-cmd-config' of github.com:prysmaticlabs/prysm into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Gaz
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Fix inits
* Merge branch 'fix-cmd-config' of github.com:prysmaticlabs/prysm into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Fix
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-cmd-config
* Fix
* Merge refs/heads/master into fix-cmd-config
* Merge refs/heads/master into fix-cmd-config
2020-08-02 22:09:10 +00:00
Ivan Martinez
22e2278812 Add heap file to E2E artifacts and fix miscalculation for deposit processing (#6657)
* Add heap file to e2e output
* Add comment
* Change to curl
* Gaz
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-heap-e2e
* Run heap at start and end
* Reorder defers
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-heap-e2e
* Fix
* Fix
* Change to logpath
* Attempt
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-heap-e2e
* Fix heap file
* Fix
* Add more beaocn nodes
* Final fixes
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-heap-e2e
* Fix slasher
* Fixes
* Fix
* Fix comment
* Merge branch 'master' into add-heap-e2e
* Merge refs/heads/master into add-heap-e2e
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-heap-e2e
* Fix comment
* Merge branch 'master' into add-heap-e2e
* Merge refs/heads/master into add-heap-e2e
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-heap-e2e
* Fix
* Change memusage to 2gb
* Merge refs/heads/master into add-heap-e2e
* Update endtoend/evaluators/metrics.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
2020-08-02 21:30:59 +00:00
Raul Jordan
eef0d058ec Refactor Direct Keymanager to One-Shot Decrypt (#6823) 2020-08-02 13:02:04 -07:00
Ivan Martinez
37343930dd Change E2E config to test deposits in PR (#6824)
* Change config to allow deposit in PR e2e

* Fix comment

* Fix

* Fix

* Fix

* Fix

* Fix

* Remove pid handling

* Fix build.bazel

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-08-01 12:22:53 -05:00
Nishant Das
002bbf53d0 Remove Custom Genesis Delay (#6827)
* remove custom delay
* gaz
* Merge branch 'master' into removeCustomGenesisDelay
2020-08-01 16:11:36 +00:00
Victor Farazdagi
bf59530d93 Adds block provider scorer (#6756)
* prepares peer scorer collection

* decouples scoring service into separate object

* updates references

* renames package

* removes redundant test init

* gazelle

* gofmt

* updates comment

* fix build

* adds block provider scorer

* score rounding factor constant (per Nishant's suggestion)

* updates penalty applying

* updates score block provider tests

* updates scorer tests

* expand test suite

* get rid of penalties + counters for requested/returned blocks

* removes start score

* fixes provider test

* fixes scorer manager tests

* updates comments

* moves roundScore test function

* maxscore tests

* improves test coverage

* Update beacon-chain/p2p/peers/score_block_providers.go

Co-authored-by: Nishant Das <nishdas93@gmail.com>

* renames var to make it less ambigous - per Nishant's suggestion

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Nishant Das <nishdas93@gmail.com>
2020-08-01 12:20:05 +03:00
Nishant Das
0e1fb65476 add bootnodes (#6807)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-31 20:34:44 -05:00
terence tsao
c7c1c660ab Load config after Configure config (#6821)
* Node: load config after configure
* Merge refs/heads/master into load-config
2020-08-01 00:46:55 +00:00
terence tsao
eb0ad0669f Fix empty wallet check (#6819) 2020-07-31 17:08:40 -07:00
Raul Jordan
4dfe02d919 Fix Accounts List Show Deposit Data When Coming From Eth2.0 Deposit CLI (#6811)
* amend accounts list when coming from launchpad
* Merge refs/heads/master into fix-accounts-list
* Merge refs/heads/master into fix-accounts-list
* Merge refs/heads/master into fix-accounts-list
* Merge refs/heads/master into fix-accounts-list
* Merge refs/heads/master into fix-accounts-list
2020-07-31 22:08:13 +00:00
Preston Van Loon
821f2ec029 Accounts V2: Allow user to override password-dir set in the wallet config (#6817)
* Accounts V2: Log a warning when a user specifies --password-dir when it has already been set.
* Override wallet config, as user intended
* gofmt
* Merge refs/heads/master into av2-flag-improvement
2020-07-31 21:20:56 +00:00
Preston Van Loon
dbd2d9a0bb Accounts V2: improve progressbar feedback (#6814)
* Accounts V2: improve progressbar feedback
* gofmt
* Merge refs/heads/master into pb-improvements
2020-07-31 20:46:03 +00:00
Preston Van Loon
3f983e2a96 Accounts V2: Allow for user to specify single file rather than directory for keystore import (#6813)
* Fix public key formatting
* Accounts V2: Allow for user to specify single file rather than directory
* Merge branch 'master' into fix-pubkey-formatting
* Merge refs/heads/master into fix-pubkey-formatting
2020-07-31 20:17:39 +00:00
Raul Jordan
7a1e5b1dd9 Allow spaces in keystore account passwords (#6810)
* allow for spaces in pass
* handle spaces with tests
* Merge refs/heads/master into handle-spaces
2020-07-31 19:50:44 +00:00
Preston Van Loon
bf82683d4f Fix public key formatting (#6809)
* Fix public key formatting
2020-07-31 19:23:08 +00:00
Preston Van Loon
323bf70b85 Add a script to tag docker images as stable or by their git tag version (#6808)
* Add a script to tag docker images as stable or by their git tag version
* Apply suggestions from code review

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
* Always use HEAD
2020-07-31 18:25:14 +00:00
Nishant Das
f414cf36b9 Revert "Reduce E2E idle time to expedite completion (#6762)" (#6793)
* Revert "Reduce E2E idle time to expedite completion (#6762)"

This reverts commit 187cae8290.
* Merge branch 'master' into revertE2EChanges
* fix
* Merge refs/heads/master into revertE2EChanges
* Change size
2020-07-31 02:42:18 +00:00
terence tsao
f7c8ae5aa6 Config flag: onyx (#6789)
* Config/flags: add onyx back
* Sync with master
* Merge refs/heads/master into onyx
* Merge refs/heads/master into onyx
* onyx flag
* Merge refs/heads/master into onyx
* Merge refs/heads/master into onyx
2020-07-31 01:23:37 +00:00
terence tsao
0cced6e41d Roughtime: use debug instead of info log (#6792)
* Roughtime: use debug instead of info log
* Merge refs/heads/master into roughtime-debug
* Merge refs/heads/master into roughtime-debug
2020-07-31 00:00:24 +00:00
Raul Jordan
18f8578d73 Derived Keymanager Has No Need to Store Accounts to Disk (#6790)
* tests pass
* Merge branch 'master' into derive-no-store
* Merge refs/heads/master into derive-no-store
* gaz
* Merge branch 'derive-no-store' of github.com:prysmaticlabs/prysm into derive-no-store
* Merge refs/heads/master into derive-no-store
2020-07-30 23:23:18 +00:00
Raul Jordan
b2ae4243fd Concurrent Decryption of Direct Keymanager Accounts With Progress Bar (#6788)
* progress bar add

* Update validator/keymanager/v2/direct/direct.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* Update validator/keymanager/v2/direct/direct.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* fix test

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-30 17:54:15 -05:00
terence tsao
0b77f4f84c Update badge to v0.12.2 (#6740)
* Update badge to v0.12.2
* Merge refs/heads/master into terencechain-patch-1
* Merge refs/heads/master into terencechain-patch-1
* Merge refs/heads/master into terencechain-patch-1
* Merge refs/heads/master into terencechain-patch-1
* Merge refs/heads/master into terencechain-patch-1
* Merge refs/heads/master into terencechain-patch-1
2020-07-30 21:56:36 +00:00
terence tsao
a116502c76 Accounts v2 as default (#6784)
* Featureconfig: invert accounts v2
* Test: fixing validator node
* Test: Fixed node test
* Merge refs/heads/master into account-v2-default
* Merge refs/heads/master into account-v2-default
* Merge refs/heads/master into account-v2-default
* Merge refs/heads/master into account-v2-default
* Merge refs/heads/master into account-v2-default
* Merge refs/heads/master into account-v2-default
2020-07-30 21:00:02 +00:00
Nishant Das
2011896005 Fix Local IP Address (#6781)
* fix local ip
* Merge refs/heads/master into fixLocalIP
* Merge refs/heads/master into fixLocalIP
* Merge refs/heads/master into fixLocalIP
* Merge refs/heads/master into fixLocalIP
* Merge refs/heads/master into fixLocalIP
* Merge refs/heads/master into fixLocalIP
* Merge refs/heads/master into fixLocalIP
2020-07-30 20:23:30 +00:00
Raul Jordan
bd7046c790 Improve Speed of Accounts Import (#6785)
* improve speed of import
* better format
* imports
* Merge branch 'master' into fast-import
* Merge refs/heads/master into fast-import
* Merge refs/heads/master into fast-import
* Merge refs/heads/master into fast-import
* Merge refs/heads/master into fast-import
2020-07-30 19:42:16 +00:00
terence tsao
ec4de10001 Add helper ComputeDomainAndSign (#6773)
* Starting
* Merge branch 'master' of github.com:prysmaticlabs/prysm into domain-and-sign
* core blocks tests: updated
* core state tests: updated
* rpc validator tests updated
* sync tests updated
* testutil updated
* Beacon-chain: update tests
* Shared: update tests
* Rest of the tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into domain-and-sign
* Merge refs/heads/master into domain-and-sign
* Merge refs/heads/master into domain-and-sign
* Merge refs/heads/master into domain-and-sign
* Merge refs/heads/master into domain-and-sign
* Sync with master
* Merge branch 'domain-and-sign' of github.com:prysmaticlabs/prysm into domain-and-sign
* Merge refs/heads/master into domain-and-sign
2020-07-30 19:11:22 +00:00
Nishant Das
edc9fcd0d6 Harden Against DOS Attacks (#6780)
* harden
* gaz
* trace log
* Update beacon-chain/p2p/service.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
* yield go-routine
* Merge refs/heads/master into hardenAgainstDOS
* Merge branch 'hardenAgainstDOS' of https://github.com/prysmaticlabs/geth-sharding into hardenAgainstDOS
* Merge refs/heads/master into hardenAgainstDOS
* Merge refs/heads/master into hardenAgainstDOS
* Merge refs/heads/master into hardenAgainstDOS
* Merge refs/heads/master into hardenAgainstDOS
2020-07-30 18:42:22 +00:00
Preston Van Loon
dec779dc1e Disable --enable-eth1-data-majority-vote in e2e (#6787)
* Disable --enable-eth1-data-majority-vote in e2e. See https://github.com/prysmaticlabs/prysm/issues/6786
* Merge refs/heads/master into disable-vote-with-majority
2020-07-30 18:14:07 +00:00
terence tsao
b56f473800 Unskip TestSetupInitialDeposits_1024Entries (#6775)
* Unskip TestSetupInitialDeposits_1024Entries
* Merge refs/heads/master into unskip-init-deposits
* Merge refs/heads/master into unskip-init-deposits
* Merge branch 'master' of github.com:prysmaticlabs/prysm into unskip-init-deposits
* Sync with master
* Merge branch 'unskip-init-deposits' of github.com:prysmaticlabs/prysm into unskip-init-deposits
* Merge refs/heads/master into unskip-init-deposits
* Merge refs/heads/master into unskip-init-deposits
* Merge refs/heads/master into unskip-init-deposits
* Merge refs/heads/master into unskip-init-deposits
2020-07-30 17:38:34 +00:00
Nishant Das
fd0383d17e Update Libp2p Deps (#6782)
* update libp2p deps
* Merge branch 'master' into updateDeps
* tidy
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into updateDeps
* Merge branch 'updateDeps' of https://github.com/prysmaticlabs/geth-sharding into updateDeps
* revert grpc
2020-07-30 16:39:57 +00:00
Ivan Martinez
48bfffbb3e Accounts-V2: Cleanup password entry and disable export (#6778)
* Cleanup prompts
* Merge branch 'master' of github.com:prysmaticlabs/prysm into cleanup-accounts-v2
* Fix
* add todo
* Merge branch 'master' of github.com:prysmaticlabs/prysm into cleanup-accounts-v2
* Clean
* Merge refs/heads/master into cleanup-accounts-v2
* Merge refs/heads/master into cleanup-accounts-v2
* Change with error
* Merge branch 'cleanup-accounts-v2' of github.com:prysmaticlabs/prysm into cleanup-accounts-v2
* Merge refs/heads/master into cleanup-accounts-v2
* cleanup and remove deposit tx file
* display deposit data
2020-07-30 15:30:19 +00:00
terence tsao
bcea2c1b22 Config/flag: medalla as default (#6770)
* config: use medalla as default

* Tests: align with medalla spec

* Config/flag: deprecate medalla feature flag

* Update shared/featureconfig/flags.go

* Spectest: set genesis forkversion to 0,0,0,0

* Config: set medalla as defat in Configure

* Extra space

* Shard: use copy

* Revert a p2p fork test

* Update default medalla for tools

* Use medalla config for e2e

* Fix E2E

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
2020-07-30 08:45:00 -05:00
Ivan Martinez
187cae8290 Reduce E2E idle time to expedite completion (#6762)
* Make changes to E2E to finish faster

* rename

* Fix

* reduce slots per epoch

* Remove process ID

* Fix

* Fix

* Fix

* Remove pid handling

* Fix build

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-29 21:58:30 -05:00
Nishant Das
353bec600f Fix Handshake (#6776)
* remove security issue
* Merge branch 'master' into fixHandshake
2020-07-30 01:04:35 +00:00
Raul Jordan
bde18f0329 Resolve Remaining Accounts Bugs (#6769)
* fix cases
* fix up imports
* ask until successful
* fixed imports flow
* fully utilize progress bar
* tidy
* grpc
* add round trip test fix
* properly use seeds
* update deps
* update deps
* tidy
* rem print
* fix bazel tests
* rem extraneous log
* gaz
* go mod tidy
* grpc version
* fix deps
* Merge branch 'master' into empty-or-nonexistent
* deps
* tidy
* option show bytes
* Merge refs/heads/master into empty-or-nonexistent
2020-07-29 23:54:23 +00:00
Raul Jordan
62c92af247 Remove Deprecated SSZ Decode Edge Case for BeaconBlocksByRoots (#6771)
* remove temp unmarshal edge case
* removed deprecated func
* final err fix
* Merge refs/heads/master into fix-exploit
2020-07-29 23:15:14 +00:00
Raul Jordan
f9a08dd5d2 Revert "Update Ethereumapis" (#6772)
* Revert "Update Ethereumapis (#6761)"

This reverts commit e94e62b98f.
2020-07-29 22:23:13 +00:00
Nishant Das
ecf197c11e Update Pubsub Parameters (#6744)
* initial commit

* fix

* lint

* clean up

* fix bug
2020-07-29 11:14:15 -05:00
Victor Farazdagi
84697a0a59 Adds peer scorer manager (#6752)
* prepares peer scorer collection
* decouples scoring service into separate object
* updates references
* renames package
* removes redundant test init
* gazelle
* gofmt
* Merge branch 'master' into peer-scorer-manager
* updates comment
* fix build
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
* Merge refs/heads/master into peer-scorer-manager
2020-07-29 09:26:46 +00:00
Raul Jordan
e5f3a30226 Allow Relative Imports in Accounts-v2 (#6758)
* add abs imports tests

* relative imports now work

* misc

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-29 11:33:28 +03:00
Preston Van Loon
e94e62b98f Update Ethereumapis (#6761)
* Update Ethereumapis
* Merge refs/heads/master into update-ethereumapis-1
* Merge refs/heads/master into update-ethereumapis-1
2020-07-29 06:03:52 +00:00
terence tsao
d6eb6d3f41 Move ValidateAttestationTime earlier for sync (#6755)
* Move time checks to the start
* Merge branch 'master' of github.com:prysmaticlabs/prysm into check-time-first
* Merge refs/heads/master into check-time-first
* Merge refs/heads/master into check-time-first
* Merge refs/heads/master into check-time-first
* Merge refs/heads/master into check-time-first
* Merge refs/heads/master into check-time-first
2020-07-29 05:31:50 +00:00
Ivan Martinez
fac5e19a17 Accounts-V2: Replace promptui with shared/promptutil (#6759)
* Add promptutil to shared/promptutil
* fixes
* comment
* Implement promptutil into accounts-v2
* gaz
* Merge branch 'master' of github.com:prysmaticlabs/prysm into implement-promptutil
* Apply suggestions from code review
* gofmt and fix all scanned input
* Merge refs/heads/master into implement-promptutil
2020-07-29 04:55:26 +00:00
Fabrice Cheng
cbd731152e Return INVALID validator status if the BLS signature is invalid (#6576)
* return INVALID status if BLS signature is invalid

* add unit tests for VerifyDepositSignature function

* fix lint

* lint fix

* gazelle run run

* update ethereumapis dependencies in go module

* tidy go mod

* update VerifyDepositSignature function to use the proper way of generating sig

* update tests

* update gazelle

* add ValidatorStatus test

* update to Warn

* reorder impot

* merge verifyDepositDataSigningRoot with VerifyDepositSignature

* refactor one last time

* align with specs for computing Domain

* add warn error logs
2020-07-28 23:19:07 -05:00
Ivan Martinez
fc0585f724 Add promptutil to shared/promptuil (#6757)
* Add promptutil to shared/promptutil
* fixes
* comment
2020-07-29 03:04:14 +00:00
Raul Jordan
9d08ba49de Accounts Revamp Fixes: "Overall" Wallet Improvements (#6736)
* change default wallet dir path to not be hidden

* gaz + pass wallet dir

* gaz + move const to flags

* move to flags

* move to flags

* use filepath join in order to create a valid dir name

* add wallet dir

* return err no wallet found issues

* fix up edit remote

* all tests passing

* fix test

* create or open wallet

* ivan feedback

* enter password for account with pubkey

* Update validator/accounts/v2/accounts_create.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* works

* preston feedback

* nothing to export

* fmt

* test for create or open

* gaz

Co-authored-by: shayzluf <thezluf@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
2020-07-28 20:20:13 -05:00
Preston Van Loon
1a1c1bb813 Return 503 on healthz with error (#6754)
* Return 503 on healthz with error
* fix other test
* Update shared/prometheus/service_test.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
2020-07-29 00:31:21 +00:00
Ivan Martinez
3a609f44b9 Accounts-V2: Minor fixes for logging (#6751)
* Fixes for accounts-v2
* Merge branch 'master' into fixes
* Undo wallet changes
* Merge branch 'fixes' of github.com:prysmaticlabs/prysm into fixes
* Merge refs/heads/master into fixes
2020-07-28 22:58:11 +00:00
terence tsao
c0d6a231bf Faster ancestor root look up via fork choice store (#6753)
* forkchoice: add `HasParent` and `AncestorRoot` getters
* Tests
* Interfaces
* process block: use getters in `ancestor`
* Update tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into faster-ancestor-block
* feedback from @rauljordan
2020-07-28 22:29:34 +00:00
rkapka
becb0b19e2 Voting With The Majority (#6644)
* eth1DataMajorityVote draft
* Merge branch 'origin-master' into eth1-majority-voting
* small test change
* move minimal config's HeadOfVotingPeriodLength closer to sqroot(32)
* remove todo
* remove head period and simplify equality check
* extract private functions from eth1DataMajorityVote
* feature flag
* Merge branch 'origin-master' into eth1-majority-voting
* add bytes import to tests
* Merge branch 'master' into eth1-majority-voting
* re-run build
* Merge branch 'master' into eth1-majority-voting
* Merge branch 'master' into eth1-majority-voting
* Merge branch 'master' into eth1-majority-voting
2020-07-28 20:29:12 +00:00
Ivan Martinez
ee1adddd24 Accounts V2: Fix issues reported by rkapka (#6725)
* Fix accounts v2 runtime
* Accounts V2: Fix issues found by rkapka
* Add to help
* Merge refs/heads/master into fix-v2-runtime
* Merge refs/heads/master into fix-v2-runtime
* Merge refs/heads/master into fix-v2-runtime
* Merge refs/heads/master into fix-v2-runtime
* Fixes
* add back error
* Make new wallet error cleaner
* Fix text
* Fix log
* Add case for normal error
* Update validator/flags/flags.go

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-v2-runtime
* Merge refs/heads/master into fix-v2-runtime
* Fix comment
* Merge refs/heads/master into fix-v2-runtime
* fix comment
* Fix test
* Merge branch 'master' into fix-v2-runtime
* Merge refs/heads/master into fix-v2-runtime
* Merge refs/heads/master into fix-v2-runtime
* Merge refs/heads/master into fix-v2-runtime
* Merge refs/heads/master into fix-v2-runtime
2020-07-28 19:23:53 +00:00
Preston Van Loon
06ee5695fb Save finalized checkpoint on beacon chain close (#6431)
* Save finalized checkpoint on save

* gofmt and goimport

* remove head.root arg

* test

* fixes

* remove comment

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-28 13:35:17 -05:00
terence tsao
027ee4c18c Add a ComputeDomainVerifySigningRoot helper (#6743)
* Add ComputeDomainVerifySigningRoot
* Update validate aggregate proof signatures to use it
* Update verify proposer slashing to use it
* Update test to use it
* Merge branch 'master' into domain-and-signingroot
* Quick fix on test
* Merge branch 'domain-and-signingroot' of github.com:prysmaticlabs/prysm into domain-and-signingroot
* Merge branch 'master' of github.com:prysmaticlabs/prysm into domain-and-signingroot
* Merge refs/heads/master into domain-and-signingroot
* Merge refs/heads/master into domain-and-signingroot
2020-07-28 16:49:47 +00:00
Nishant Das
8a69d34b96 Fix Accounts Creation Error (#6748)
* add check
* Merge refs/heads/master into fixAccountsError
* Merge refs/heads/master into fixAccountsError
2020-07-28 16:06:18 +00:00
Nishant Das
7861005990 Allow Multiple Selection For Exports (#6749)
* add changes
* Merge branch 'master' into fixExports
* last request
* Merge branch 'fixExports' of https://github.com/prysmaticlabs/geth-sharding into fixExports
2020-07-28 15:31:37 +00:00
Ivan Martinez
607d5fdf4e Accounts-V2: Change accounts-v2 import to use directory of keystores (#6742)
* Finish implementation of importing dir of keystores

* Fix

* Fix importing

* Finish testing import account

* Update validator/accounts/v2/accounts_import.go

* Fix

* Fix

* fix

* Fix prompt

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-07-28 09:18:22 -05:00
Ivan Martinez
0cd80bb970 Accounts-V2: Change keystore filename to include timestamp (#6741)
* Change keystore filename to include timestamp
* Fix test
* Merge branch 'master' into change-keystore-filename
* Fix comment
* Merge branch 'change-keystore-filename' of github.com:prysmaticlabs/prysm into change-keystore-filename
* Request comments
* Comment
* Add comment
* Fix test
* Fix test
* Add test for AccountTimestamp
2020-07-28 00:02:29 +00:00
Shay Zluf
a867f6175b Make external slasher protection fail on load if slasher is not reachable (#6704)
* external slasher protection fails loudly
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge branch 'master' of github.com:prysmaticlabs/prysm into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* Merge refs/heads/master into external-slasher-fail-loud
* ivan feedback
* Merge branch 'external-slasher-fail-loud' of github.com:prysmaticlabs/prysm into external-slasher-fail-loud
* lint fix
* ivan feedback
2020-07-27 20:06:49 +00:00
terence tsao
905a57cbd7 Fix checkForChainStart pre-genesis state and 0 validator (#6739) 2020-07-27 10:35:01 -07:00
Ivan Martinez
7fff4ec411 Accounts V2: Add --num-accounts to HD wallet commands (#6721)
* Add num-accounts to wallet recover and account create for derived wallets

* Fix

* Test derived accounts

* Stuff

* Gaz

* Fix

* Fix

* Fix test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-27 09:03:30 -05:00
Nishant Das
664349e553 Account for Bad Blocks in Gossip (#6726)
* add bad block cache

* terence's review

* terence's review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-27 19:57:19 +08:00
terence tsao
3a852bc032 eth1 chain ID and network checks (#6727)
* Add config
* Update config values
* Add checks
* Merge refs/heads/master into eth1network
* Merge refs/heads/master into eth1network
* Update e2e test config for devnet
* Merge branch 'eth1network' of github.com:prysmaticlabs/prysm into eth1network
2020-07-27 04:48:36 +00:00
Victor Farazdagi
630cbfb1b6 Fixes issue with concurrent map writes in gossipsub (#6731)
* Fixes issue with concurrent map writes in gossipsub
* Merge refs/heads/master into fix-concurrent-map-write-in-pubsub
2020-07-27 00:56:55 +00:00
terence tsao
ca04621849 saveHeadNoDB does not invalidate hot state cache (#6729) 2020-07-26 17:10:35 -07:00
Nishant Das
c8761ffb18 Revert "Update rules go to v0.22.9 (#6712)" (#6724)
This reverts commit efc24f6aab.
2020-07-26 12:28:42 +08:00
Nishant Das
2cd359bde5 preset memory (#6722) 2020-07-25 11:54:54 -07:00
Nishant Das
7a12fc6d75 Fix Metadata Sequence Checks (#6711)
* checkpoint

* Update beacon-chain/sync/rpc_test.go

* change conditional

* fix test

* fmt

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-25 11:53:41 -05:00
Nishant Das
ada351d087 Applies Assertion And Require Test Functions to Powchain (#6652)
* change all tests
* save
* fix tests
* Update deposit_test.go
* Update deposit_test.go
* Update log_processing_test.go
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* fix failing test
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
* Merge refs/heads/master into powchainAssert
2020-07-25 06:20:21 +00:00
terence tsao
d114c6c6b7 Update comments for get_committee_count_per_slot (#6717)
* Update comment
* Merge branch 'master' into epochwise_committee_count_per_slot
* Merge refs/heads/master into epochwise_committee_count_per_slot
* Merge refs/heads/master into epochwise_committee_count_per_slot
* Merge refs/heads/master into epochwise_committee_count_per_slot
* Merge refs/heads/master into epochwise_committee_count_per_slot
* Merge refs/heads/master into epochwise_committee_count_per_slot
* Merge refs/heads/master into epochwise_committee_count_per_slot
2020-07-25 05:29:30 +00:00
terence tsao
01f3a6e6db Update on block/attestation comments (#6720)
* Update on att comments
* Update on block comments
* Merge refs/heads/master into forkchoice-comments
* Merge refs/heads/master into forkchoice-comments
2020-07-25 04:55:42 +00:00
Preston Van Loon
efc24f6aab Update rules go to v0.22.9 (#6712)
* bump rules_go

* reapply patch, remove commented code

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-25 12:14:17 +08:00
Preston Van Loon
715a33532d Update ethereumapis (#6719)
* Update ethereumapis
* go mod tidy
* Merge refs/heads/master into update-ethereumapis
2020-07-25 01:03:59 +00:00
terence tsao
366e53c416 Add committee ID check to process attestation (#6718) 2020-07-24 17:12:15 -07:00
Preston Van Loon
e1f33b196d Update spectests to v0.12.2 (#6713)
* Update spectests to v0.12.2
* Update readme to v0.12.2
* Revert "Update readme to v0.12.2"

This reverts commit 34461a1d05.
* Merge branch 'master' into update-spectests-v0.12.2
* fix config path
* Merge refs/heads/master into update-spectests-v0.12.2
2020-07-24 22:25:31 +00:00
Raul Jordan
55009bfa66 Fix Validator Accounts-V2 Runtime (#6714)
* fix accounts v2 runtime
2020-07-24 21:36:28 +00:00
terence tsao
0b9212c685 Revert "Optimize AppendValidator for beacon state" (#6710)
* Revert "Optimize `AppendValidator` for beacon state (#6659)"

This reverts commit c41e382255.
* Test. H/t to @prestonvanloon
* Merge branch 'master' of github.com:prysmaticlabs/prysm into revert-6659-deposit
* Merge branch 'master' into revert-6659-deposit
2020-07-24 05:43:15 +00:00
terence tsao
403dab43f5 Use config DepositContractTreeDepth (#6708) 2020-07-23 21:30:28 -07:00
Ivan Martinez
dfdff37a3e Accounts V2: Fix import command (#6707)
* Fix import
* Merge branch 'master' into fix-import-v2
* Fix
* Merge branch 'fix-import-v2' of github.com:prysmaticlabs/prysm into fix-import-v2
* Fix for comments
* Merge refs/heads/master into fix-import-v2
* Merge branch 'master' into fix-import-v2
2020-07-24 03:19:28 +00:00
Ivan Martinez
3974104a20 Accounts V2: Rename new->create, rename files and usage text fixes (#6695)
* Accounts V2: Renames and usage text fixes

* Fix
2020-07-23 21:18:36 -05:00
Raul Jordan
a5b408769a Accounts V2: Resolve Remaining Keymanager Bugs (#6706)
* v2 fix bugs
* better doc
* include wallet build fix
* fixed broken list test
* add round trip recover seed unit test
* imports
* implement list with tests
* add altona flags
* tests for unicode
* added is valid unicode tests
* fixed up tests to ensure wallet is persisted after everything works
* resolve confs and integrate medalla testnet
* fix build
* add medalla
* fixed import spacing
2020-07-24 00:43:01 +00:00
terence tsao
cc773a1641 Rm unused HashTreeRootState (#6697)
* Remove hash tree root implementations

* Delete benchmark tests

* Update existing tests

* Gaz

* Remove outdated ssz cache fuzz test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-23 17:19:05 -05:00
Jim McDonald
415cb9ff8d Add medalla testnet configuration. (#6700) 2020-07-23 14:56:39 -05:00
Preston Van Loon
2c11fcb242 Stategen: always invalidate hot cache state in StateByRootInitialSync (#6698)
* Stategen: always invalidate hot cache state in StateByRootInitialSync
* Sanity test. @nisdas feedback
* Merge refs/heads/master into defer-invalidate
2020-07-23 04:25:50 +00:00
Ivan Martinez
c72db6f96a Accounts V2: Refactor prompts, deduplicate into directory and password (#6674)
* Refactor input code, deduplicate into directory and password
* Change to filepath
* Rename
* Make consts visible to whole validator package
* Fix
* Try commands and fix
* Fix defaults
* Fixes
* Merge branch 'master' into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Remove consts and add comment
* Merge branch 'refactor-input-prompts' of github.com:prysmaticlabs/prysm into refactor-input-prompts
* Undo
* Fixes
* Update validator/accounts/v2/prompt.go
* Merge refs/heads/master into refactor-input-prompts
* gofmt
* Merge refs/heads/master into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Merge branch 'master' into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Fix
* Merge refs/heads/master into refactor-input-prompts
* Merge refs/heads/master into refactor-input-prompts
* Accounts V2: Simplify Wallet Save/Read To and From Disk Functions (#6686)

* simplify wallet functions

* fix build

* futher simplify wallet

* simplify read/write methods

* move direct functions to direct keymanager

* further move direct km specific funcs

* cleanup

* simplify the direct tests

* fixed tests

* lint

* further simplify

* tidy

* fix config write

* fixed test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* conflict resolution
* trim
2020-07-23 03:10:23 +00:00
Raul Jordan
7c52ef8c2b Accounts V2: Simplify Wallet Save/Read To and From Disk Functions (#6686)
* simplify wallet functions

* fix build

* futher simplify wallet

* simplify read/write methods

* move direct functions to direct keymanager

* further move direct km specific funcs

* cleanup

* simplify the direct tests

* fixed tests

* lint

* further simplify

* tidy

* fix config write

* fixed test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-22 21:12:51 -05:00
Victor Farazdagi
0006377aec Applies assertion funcs to validator tests (#6694)
* Applies assertion funcs to validator/keymanager/v1 tests
* gazelle
* Applies assertion funcs to validator/keymanager/v2 tests
* Applies assertion funcs to validator/misc tests
* Applies assertion funcs to validator/misc tests
* Merge branch 'master' into validator-apply-testutils-assertions
* gazelle
* Merge branch 'master' into validator-apply-testutils-assertions
* Merge branch 'master' into validator-apply-testutils-assertions
* Merge refs/heads/master into validator-apply-testutils-assertions
2020-07-23 01:13:52 +00:00
Preston Van Loon
208659d7f5 Enable local slashing protection by default (#6687)
* Enable local slashing protection by default
* Merge refs/heads/master into enable-local-protection-by-default
* Merge refs/heads/master into enable-local-protection-by-default
* Merge refs/heads/master into enable-local-protection-by-default
* Merge refs/heads/master into enable-local-protection-by-default
* Merge refs/heads/master into enable-local-protection-by-default
* Merge refs/heads/master into enable-local-protection-by-default
2020-07-23 00:47:19 +00:00
Ivan Martinez
cf57db910c Accounts V2: Remove traces from command errors (#6692)
* Remove traces from errors for accounts command
* Merge refs/heads/master into remove-stack
* Merge refs/heads/master into remove-stack
* Merge refs/heads/master into remove-stack
* Merge refs/heads/master into remove-stack
* Merge refs/heads/master into remove-stack
2020-07-23 00:11:00 +00:00
Ivan Martinez
73a9429f1e Accounts V2: Remove CanUnlockAccounts from Wallet (#6693)
* Remove CanUnlockAccounts from Wallet
* Merge refs/heads/master into remve-canunlockaccounts
* Merge refs/heads/master into remve-canunlockaccounts
* Merge refs/heads/master into remve-canunlockaccounts
2020-07-22 23:26:39 +00:00
Raul Jordan
cab89c37f1 Accounts V2: Remove Mnemonic Confirm From Direct Keymanager (#6696)
* remove mnemonic from direct
* Merge refs/heads/master into remove-mnemonic-direct
2020-07-22 22:52:31 +00:00
Ivan Martinez
7d80415089 Move deposit utils to depositutil package (#6690)
* Move deposit utils to depositutil package
* gofmt
* Gaz
* Merge refs/heads/master into move-deposit-utils
* Merge refs/heads/master into move-deposit-utils
2020-07-22 22:21:41 +00:00
Preston Van Loon
f19770a393 Revert "Add Github Superlinter" (#6691)
* Revert "Add Github Superlinter (#6677)"

This reverts commit 6270347fdb.
* Merge refs/heads/master into revert-6677-rauljordan-patch-1
2020-07-22 21:48:04 +00:00
rkapka
95efcb6410 Applies assertion funcs to forkchoice tests (#6685)
* refactored 3 files
* refactored the rest of files
* Merge branch 'origin-master' into refactor-forkchoice-tests
* gazelle fix
* Merge branch 'master' into refactor-forkchoice-tests
* Merge branch 'master' into refactor-forkchoice-tests
* Merge branch 'master' into refactor-forkchoice-tests
2020-07-22 21:11:03 +00:00
Raul Jordan
6270347fdb Add Github Superlinter (#6677)
* Add Github Superlinter

This PR adds the Github superlinter to our codebase as a Github action. Resolves #6308.
* Apply suggestions from code review
* Merge refs/heads/master into rauljordan-patch-1
* fix action
* Merge refs/heads/master into rauljordan-patch-1
* Merge refs/heads/master into rauljordan-patch-1
* Merge refs/heads/master into rauljordan-patch-1
* Merge refs/heads/master into rauljordan-patch-1
* Merge refs/heads/master into rauljordan-patch-1
2020-07-22 20:22:26 +00:00
Victor Farazdagi
e5b7c3f3e6 Applies assertion funcs to validator/keymanager tests (#6683)
* Applies assertion funcs to validator/keymanager/v1 tests
* gazelle
* Applies assertion funcs to validator/keymanager/v2 tests
* Merge refs/heads/master into validator-keymanager-apply-testutils-assertions
* Merge refs/heads/master into validator-keymanager-apply-testutils-assertions
2020-07-22 19:42:43 +00:00
terence tsao
6c408d31df Remove unused protos and operations (#6684)
* Remove attestation containers

* Remove unused last votes

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-22 14:05:41 -05:00
Victor Farazdagi
4400321081 Handles case when no peers with finalized blocks are found (#6679)
* Handles case when no peers with finalized blocks are found
* more tests
* Merge branch 'master' into handle-zero-block-init-sync
* Merge branch 'master' into handle-zero-block-init-sync
2020-07-22 18:14:24 +00:00
terence tsao
17f845dcb0 Update head before send feed (#6681)
* Update head before state feed
* Test
* Merge branch 'master' of github.com:prysmaticlabs/prysm into update-head
2020-07-22 17:05:17 +00:00
Preston Van Loon
62ae22e3f9 Use correct context for chainHeadRetrieval (#6678)
* Use correct context for chainHeadRetrieval
* Merge refs/heads/master into fix-context
2020-07-22 16:20:20 +00:00
Nishant Das
647599e87f fix for virtual networks (#6676) 2020-07-22 10:44:17 -05:00
Raul Jordan
4017743f7f Accounts V2: Refactor Wallet Open / Close and Keymanager Initialization (#6668)
* refactoring create account

* dep

* much easier, create a derived account by simply unlocking wallet

* revert changes to new

* make open wallet smarter and utilize cli ctx

* remove the wallet config

* successfully build

* simplify ctx creation for tests

* tests should pass individually

* tests pass

* fixed up to allow for wallet password file input

* fix broken tests

* formatting

* fmt

* simplify recover

* fixed up tests

* implicit use of default wallet path working

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-21 23:49:04 -05:00
Preston Van Loon
28096a846e Better gRPC retry including stream retry (#6670)
* Add gRPC retry delay, apply retry and delay to streams

* gofmt, fix flag

* lint

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-21 22:45:52 -05:00
Ivan Martinez
e0d11ff1d2 Accounts V2: Wallet Recover (#6661)
* Implement derived wallet recover
* Fix log
* Fix tests
* Comments
* Merge branch 'master' of github.com:prysmaticlabs/prysm into derived-recover
* Remove log
* Comments
* Fix fatal
* add comment
* Merge refs/heads/master into derived-recover
* Merge refs/heads/master into derived-recover
* Merge refs/heads/master into derived-recover
* Merge refs/heads/master into derived-recover
2020-07-22 02:41:39 +00:00
Ivan Martinez
8a65af168d Accounts V2: Change fatal logs to return errors (#6672)
* Change logging out errors to returns
* Merge branch 'master' of github.com:prysmaticlabs/prysm into change-logs-to-return
* Lint
* Merge branch 'master' into change-logs-to-return
2020-07-22 02:04:08 +00:00
terence tsao
d1a828ad87 Rm archival service db usages and proto definitions (#6671) 2020-07-21 17:04:46 -07:00
Preston Van Loon
f1cfb6a222 Update go-ethereum (#6660)
* Update go-ethereum
* fix go-ethereum
* Merge branch 'master' into update-go-ethereum
* Merge refs/heads/master into update-go-ethereum
* Merge refs/heads/master into update-go-ethereum
* Merge refs/heads/master into update-go-ethereum
2020-07-21 21:52:19 +00:00
Raul Jordan
3023f5dbd3 Accounts V2: Derived Keymanager Sign (#6667)
* amend derived with secret keys cache
* all tests for sign
* Merge branch 'master' into sign-derived
* formatting
* Merge branch 'sign-derived' of github.com:prysmaticlabs/prysm into sign-derived
* initialize
* use seed
* fix build
* Merge refs/heads/master into sign-derived
* Merge refs/heads/master into sign-derived
* Update validator/keymanager/v2/derived/derived.go
2020-07-21 21:15:47 +00:00
terence tsao
c41e382255 Optimize AppendValidator for beacon state (#6659) 2020-07-21 12:58:30 -07:00
Preston Van Loon
784f4169ef Check gossip message decoded length before decoding (#6663)
* Check gossip message decoded length before decoding
* gofmt
* Merge refs/heads/master into snappy-decodedlen-check
* Merge refs/heads/master into snappy-decodedlen-check
* Merge refs/heads/master into snappy-decodedlen-check
* @nisdas feedback
2020-07-21 19:14:34 +00:00
terence tsao
367738e83b Remove unused attestation operations in DB (#6664)
* Remove attestation usages in DB
* Merge refs/heads/master into rm-unused
* Merge refs/heads/master into rm-unused
* Fixed export wrapper
* Merge branch 'rm-unused' of github.com:prysmaticlabs/prysm into rm-unused
2020-07-21 18:17:33 +00:00
Victor Farazdagi
ca54c1d480 Applies assertion funcs to validator/client tests (#6654)
* Applies assertion funcs to validator/client tests
* gazelle
* Merge branch 'master' into validator-client-apply-testutils-assertions
* Merge refs/heads/master into validator-client-apply-testutils-assertions
* Merge refs/heads/master into validator-client-apply-testutils-assertions
* Merge refs/heads/master into validator-client-apply-testutils-assertions
* Merge refs/heads/master into validator-client-apply-testutils-assertions
* Merge refs/heads/master into validator-client-apply-testutils-assertions
* Merge refs/heads/master into validator-client-apply-testutils-assertions
2020-07-21 13:02:21 +00:00
Raul Jordan
e97d310453 Accounts V2: Derived Keymanager List Accounts (#6662)
* begin on list derived accounts
* begin on list derived accounts
* continued work on listing derived accounts
* deterministic pet name
* petnames
* finished list
* display deposit data
* lint
* use direct km
* tidy
* begin on revising tests for accounts list
* fix direct list test
* gaz
* tests all passing for derived list
* gaz
2020-07-21 05:06:11 +00:00
Raul Jordan
bc16fa9f50 Accounts V2: Derived Keymanager, Wallet & Account Creation (#6624)
* initialize derived wallet
* derived wallet + account creation
* initialize wallet seed
* encrypted seed file creation
* generate next acct
* create seed from pass
* properly creating derived accounts
* fix up formatting
* prep for review
* start tests for derived create account
* add derived test
* linter
* gaz
* derived keymanager create account test complete
* Merge branch 'master' into derived-keymanager
* tests pass
* gaz
* fix list test
* Merge refs/heads/master into derived-keymanager
* ivan feedback
* skip mnemonic confirm
* Merge branch 'derived-keymanager' of github.com:prysmaticlabs/prysm into derived-keymanager
* comment
* tidy
* fmt
* organize
* test interface conformity
* Update validator/accounts/v2/iface/wallet.go
* ivan comments
* Merge branch 'derived-keymanager' of github.com:prysmaticlabs/prysm into derived-keymanager
* Merge refs/heads/master into derived-keymanager
* Merge branch 'master' of github.com:prysmaticlabs/prysm into derived-keymanager
* Fix
* Fix test
* Merge refs/heads/master into derived-keymanager
* fix errs
* imports
* Gaz
2020-07-21 02:05:23 +00:00
Victor Farazdagi
9deeb592e6 Adds type info into equality assertions (#6656)
* Adds type info into equality assertions
* tests
* reorder got/want
* more tests
* Merge refs/heads/master into assertions-better-error-reporting
* Merge refs/heads/master into assertions-better-error-reporting
* Merge refs/heads/master into assertions-better-error-reporting
2020-07-21 00:47:53 +00:00
Ivan Martinez
93bbb86a30 Accounts-V2: Add tests for exporting and importing (#6615)
* Add test for exporting and importing
* Add test for non-interactive
* Test import cli
* Merge branch 'master' of github.com:prysmaticlabs/prysm into test-export
* Merge branch 'master' into test-export
* Cleanup tests a bit
* Change to assert
* Fix tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into test-export
* Fix comment, change constants
* Fixes
* Change to require
* Fix broken test
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
* Merge refs/heads/master into test-export
2020-07-20 21:12:46 +00:00
Ivan Martinez
d54663a553 Add --historical-slasher-node flag to simplify slasher usage (#6627)
* Add historical-slasher-node flag
* Fix build
* Remove useless flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Fix flag
* Merge branch 'add-flasher-flag' of github.com:prysmaticlabs/prysm into add-flasher-flag
* Add flags to beacon chain
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
* Merge refs/heads/master into add-flasher-flag
2020-07-20 20:23:48 +00:00
terence tsao
0488c9869e Init sync batch block clean up (#6599) 2020-07-20 12:35:30 -07:00
Victor Farazdagi
f0ffd5af03 Introduces peer scorer service (#6579)
* introduces peer scorer service
* gazelle
* Merge branch 'master' into peer-scoring-service
* fixes comment
* fix build error
* linter suggestions
* Merge branch 'master' into peer-scoring-service
* updates tests
* Merge branch 'master' into peer-scoring-service
* badresponses scorer tests
* gazelle
* Merge branch 'master' into peer-scoring-service
* Merge branch 'master' into peer-scoring-service
* adds scorer_test
* gazelle
* updates bad response default penalty
* more comments
* Merge branch 'master' into peer-scoring-service
* Merge branch 'master' into peer-scoring-service
* Merge branch 'master' into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* introduces peerdatastore into status
* makes sure that commong peer data store is used
* Merge branch 'peer-scoring-service' of github.com:prysmaticlabs/prysm into peer-scoring-service
* linter
* gazelle
* updates tests
* Merge branch 'master' into peer-scoring-service
* fixes tests
* Nishant's suggestions
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge refs/heads/master into peer-scoring-service
* Merge branch 'master' into peer-scoring-service
* gofmt
* Nishant's suggestion to use isBadPeer
* Merge refs/heads/master into peer-scoring-service
2020-07-20 15:12:59 +00:00
Victor Farazdagi
22141db319 Applies assertion funcs to validator/accounts tests (#6653)
* Applies assertion funcs to validator/accounts tests
* Applies assertion funcs to validator/accounts tests
2020-07-20 10:56:45 +00:00
Victor Farazdagi
10d3275638 Applies assertion funcs to rpc tests (#6641)
* applies assertion funcs to beacon-chain/rpc tests
* Merge branch 'master' into rpc-apply-testutils-assertions
* applies assertion funcs to beacon-chain/rpc/beacon tests
* Merge branch 'master' into rpc-apply-testutils-assertions
* applies assertion funcs to beacon-chain/rpc/debug tests
* applies assertion funcs to beacon-chain/rpc/validator tests
* Merge branch 'master' into rpc-apply-testutils-assertions
* Merge refs/heads/master into rpc-apply-testutils-assertions
2020-07-20 02:15:51 +00:00
Victor Farazdagi
1d0fe105fc Extends assertions to accept fmt params (#6645)
* Extends assertions to accept fmt params
2020-07-20 01:36:28 +00:00
terence tsao
0544dd1f8e Applies assertion funcs to shared tests (#6643)
* cmd tests
* deposit util tests
* feature config tests
* hashutil tests
* htr util tests
* interop tests
* ip util tests
2020-07-19 21:08:29 +00:00
Preston Van Loon
b60a965981 ProcessAttestations: Add requirement that inclusion distance is not zero (#6642)
* Add requirement that inclusion distance is not zero, add regression test
* fix test input data
* Merge refs/heads/master into fix-panic
* Merge refs/heads/master into fix-panic
2020-07-19 16:38:45 +00:00
terence tsao
38c8393e52 Revert "Fixes issue with vals order in assert.Equal" (#6640)
* Revert "Fixes issue with vals order in assert.Equal (#6631)"

This reverts commit d535cb95d8.
* Merge branch 'master' into revert-6631-assertions-less-assuming-error-msg
2020-07-19 04:45:04 +00:00
Victor Farazdagi
568238009e Extracts peer data store in p2p/peers status (#6639)
* introduces peer data store to p2p/peers
* Merge refs/heads/master into p2p-extract-data-store
* Merge refs/heads/master into p2p-extract-data-store
* refactores status service
* Merge branch 'p2p-extract-data-store' of github.com:prysmaticlabs/prysm into p2p-extract-data-store
* updates tests
* gofmt
* rever decay test
2020-07-19 03:45:08 +00:00
Preston Van Loon
c419e4ed8f Improved cold state checkpoints: migrate database index and usage (#6461)
* Add database migrations, still need to update the API usage...
* gofmt goimports
* progress
* Merge branch 'master' of github.com:prysmaticlabs/prysm into index-migration
* use slot instead of index
* rename LastArchivedIndex to LastArchivedSlot
* rename LastArchivedIndexRoot to LastArchivedRoot
* remove unused HighestSlotStates method
* deprecate old key, include in migration
* deprecate old key, include in migration
* remove blocks index in migration
* rename bucket variable
* fix code to pass tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into index-migration
* gofmt, goimports
* fix
* Add state slot index
* progress
* lint
* fix build
* Merge branch 'master' of github.com:prysmaticlabs/prysm into index-migration
* kafka
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* remove SaveArchivedPointRoot, a few other big changes
* Merge branch 'index-migration' of github.com:prysmaticlabs/prysm into index-migration
* fix tests and lint
* lint again
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* block migration, some renaming
* gaz, gofmt
* add tests
* change index to uint bytes
* Merge branch 'index-migration' of github.com:prysmaticlabs/prysm into index-migration
* rm method notes
* stop if the bucket doesn't exist
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* @rauljordan pr feedback
* Simplify
* Merge refs/heads/master into index-migration
* Remove unused method, add roundtrip test
* gofmt
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge refs/heads/master into index-migration
* Merge branch 'master' of github.com:prysmaticlabs/prysm into index-migration
2020-07-18 18:05:04 +00:00
terence tsao
d53539499c Applies assertion funcs to shared tests (part 1) (#6626)
* Update kv aggregated_test.go
* Update block_test.go
* Update forkchoice_test.go
* Update unaggregated_test.go
* Update prepare_forkchoice_test.go
* Update prune_expired_test.go
* Update atts service_test.go
* Update service_attester_test.go
* Update service_proposer_test.go
* Upate exit service_test.go
* Gaz
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Move averageBalance from log.go to info.go
* Move avg balance from log.go to info.go
* Add info test
* Remove unused logEpochData in log.go
* Gaz
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* aggregation tests
* attestation util tests
* bench util tests
* block util tests
* herumi tests
* bytesutil tests
* Merge refs/heads/master into testutil-shared
* Merge refs/heads/master into testutil-shared
* Merge refs/heads/master into testutil-shared
* Merge refs/heads/master into testutil-shared
* Merge refs/heads/master into testutil-shared
* Update shared/aggregation/attestations/attestations_test.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
* Merge branch 'master' of github.com:prysmaticlabs/prysm into testutil-shared
* Fixed ordering
* Merge branch 'testutil-shared' of github.com:prysmaticlabs/prysm into testutil-shared
* Update shared/aggregation/attestations/attestations_test.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
* Update shared/bytesutil/bytes_test.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
2020-07-18 16:31:42 +00:00
Victor Farazdagi
d535cb95d8 Fixes issue with vals order in assert.Equal (#6631)
* fixes issue with vals order in assert.Equal
2020-07-18 11:14:50 +00:00
Victor Farazdagi
7ba500c417 Applies assertion funcs to state tests (#6623)
* applies assertion funcs to beacon-chain/state tests
* applies assertion funcs to beacon-chain/state/stategen tests
* applies assertion funcs to beacon-chain/state/stateutil tests
* gazelle
* Merge refs/heads/master into state-apply-testutils-assertions
* Merge refs/heads/master into state-apply-testutils-assertions
* Merge refs/heads/master into state-apply-testutils-assertions
2020-07-18 07:56:48 +00:00
Preston Van Loon
c573306621 Check for array out of bounds when calculating proposer delta -- follow up (#6630)
* failing test
* fix
2020-07-18 06:39:43 +00:00
Preston Van Loon
5336a167af Check for array out of bounds when calculating proposer delta (#6629)
* Check for array out of bounds when calculating proposer delta
* Merge refs/heads/master into proposer-delta-bug
2020-07-18 04:31:03 +00:00
Preston Van Loon
0e4cb68249 Add regression test found by fuzzer (#6628)
* Add regression test found by fuzzer
2020-07-18 03:47:03 +00:00
Nishant Das
cc3c3a0c54 QSP 29: Add Rate Limiter For All Topics (#6606)
* initial commit
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into rateLimiter
* finally
* add mutex
* rate limiter for all rpc reqs
* remove recursive readlocks
* spelling
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* fix all tests
* fix all tests
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
* Merge refs/heads/master into rateLimiter
2020-07-17 08:58:51 +00:00
Raul Jordan
9ad6277852 Accounts V2: Create Wallet Non-Interactively + Add Test Coverage (#6611)
* create wallet noninteractively
* tests for wallet create
* kapol feedback
* Merge refs/heads/master into create-wallet-tests
* Merge refs/heads/master into create-wallet-tests
2020-07-17 08:21:16 +00:00
terence tsao
ebd05fba01 Improve test coverage info.go (#6618)
* Update kv aggregated_test.go
* Update block_test.go
* Update forkchoice_test.go
* Update unaggregated_test.go
* Update prepare_forkchoice_test.go
* Update prune_expired_test.go
* Update atts service_test.go
* Update service_attester_test.go
* Update service_proposer_test.go
* Upate exit service_test.go
* Gaz
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Move averageBalance from log.go to info.go
* Move avg balance from log.go to info.go
* Add info test
* Remove unused logEpochData in log.go
* Gaz
* Merge branch 'master' into info-cov
* gaz
* Merge refs/heads/master into info-cov
2020-07-16 22:44:43 +00:00
rkapka
eb0d70814a Fixed nil pointer error in DepositCache (#6596) 2020-07-16 14:48:36 -07:00
rkapka
77607c6fdb Applies assertion funcs to cache tests (#6617)
* testutils for cache
* Merge branch 'master' into cache-test-refactor
* removed some empty lines
* Merge branch 'origin-master' into cache-test-refactor
* Merge remote-tracking branch 'rkapka/cache-test-refactor' into cache-test-refactor
* revert package names
2020-07-16 19:34:08 +00:00
Nishant Das
cf2bbec6a8 Use Faster Hash Function (#6616)
* change to proto hash

* gaz

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-16 10:19:14 -05:00
terence tsao
69a2dc2716 Improve test coverage receive_block.go (#6613)
* Update kv aggregated_test.go
* Update block_test.go
* Update forkchoice_test.go
* Update unaggregated_test.go
* Update prepare_forkchoice_test.go
* Update prune_expired_test.go
* Update atts service_test.go
* Update service_attester_test.go
* Update service_proposer_test.go
* Upate exit service_test.go
* Gaz
* TestService_ReceiveBlockInitialSync
* TestService_ReceiveBlockBatch
* TestService_HasInitSyncBlock
* Merge branch 'master' of github.com:prysmaticlabs/prysm into rcv-blk-cov
* Merge branch 'master' of github.com:prysmaticlabs/prysm into rcv-blk-cov
* Merge branch 'rcv-blk-cov' of github.com:prysmaticlabs/prysm into rcv-blk-cov
* Gaz
* Merge refs/heads/master into rcv-blk-cov
* Merge refs/heads/master into rcv-blk-cov
* Merge refs/heads/master into rcv-blk-cov
* Merge refs/heads/master into rcv-blk-cov
2020-07-16 13:34:34 +00:00
Raul Jordan
d897640625 Add YAML Struct Tag to Eth1FollowDistance Parameter (#6612)
* add yaml struct tag to eth1 follow distance
* more config values missing yaml tags
* Merge refs/heads/master into follow-distance-struct-tag
* Merge refs/heads/master into follow-distance-struct-tag
* Merge refs/heads/master into follow-distance-struct-tag
2020-07-16 13:04:59 +00:00
Victor Farazdagi
deb025f57c Applies assertion funcs to blockchain tests (#6605)
* applies assertion funcs to blockchain tests
* Merge branch 'master' into blockchain-apply-testutils-assertions
* gofmt
* Merge refs/heads/master into blockchain-apply-testutils-assertions
* Merge refs/heads/master into blockchain-apply-testutils-assertions
* Merge refs/heads/master into blockchain-apply-testutils-assertions
* Merge refs/heads/master into blockchain-apply-testutils-assertions
* Merge refs/heads/master into blockchain-apply-testutils-assertions
2020-07-16 12:11:39 +00:00
Nishant Das
f6756bb591 QSP 23: Prune Peers From Peer Handler (#6614)
* checkpoint
* Merge refs/heads/master into prunePeers
2020-07-16 10:09:51 +00:00
Raul Jordan
df73851749 Accounts Revamp: Wallet Edit-Config (#6607)
* edit remote config
* gets messed up when writing to file again
* proper editing
* noninteractive mode
* test for edit wallet
* Merge branch 'master' into edit-wallet
* wallet edit test done
* imports
* Merge refs/heads/master into edit-wallet
* Merge refs/heads/master into edit-wallet
2020-07-16 05:08:16 +00:00
Ivan Martinez
fbeba94a92 Change accounts-v2 import and export to be non-interactive (#6609)
* Change import and export to be non-interactive
* Fix
* fix lint
* Merge branch 'master' into make-export-import-nonint
* Comments
* Merge branch 'make-export-import-nonint' of github.com:prysmaticlabs/prysm into make-export-import-nonint
* Merge refs/heads/master into make-export-import-nonint
2020-07-15 23:00:00 +00:00
Victor Farazdagi
a0e5754464 Resolves possible import cycle in testutils assertions (#6610)
* resolves possible import cycle in testutils assertions
* gazelle
* linter
* linter
2020-07-15 20:10:54 +00:00
terence tsao
c309ba6a10 Applies assertion funcs to operation tests (#6608)
* Update kv aggregated_test.go
* Update block_test.go
* Update forkchoice_test.go
* Update unaggregated_test.go
* Update prepare_forkchoice_test.go
* Update prune_expired_test.go
* Update atts service_test.go
* Update service_attester_test.go
* Update service_proposer_test.go
* Upate exit service_test.go
* Gaz
2020-07-15 18:37:51 +00:00
Victor Farazdagi
c2615168d9 Applies assertion funcs to sync tests (#6603)
* applies assertion funcs to sync/initial-sync tests
* applies assertion funcs to sync/initial-sync tests
* gazelle
* Merge branch 'master' into sync-apply-testutils-assertions
* gazelle
* applies assertion funcs to sync/initial-sync tests
* applies assertion funcs to sync/initial-sync tests
* applies assertion funcs to sync/initial-sync tests
* applies assertion funcs to sync/initial-sync tests
* applies assertion funcs to sync/initial-sync tests
* Merge branch 'master' into sync-apply-testutils-assertions
2020-07-15 04:41:11 +00:00
Raul Jordan
f12f75224e Accounts V2: Create Wallet via CLI (#6543)
* begin on the proto definitions

* define remote signer service protos

* basic implementation

* remote keymanager docs

* finalize remote client doc

* amend response

* fix proto defs

* test new and begin test sign

* test sign done

* remote oneof

* rename

* fix build

* viz

* Update validator/keymanager/v2/remote/remote_test.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* Update validator/accounts/v2/wallet.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* fmt

* move the input check to accounts new

* begin on requesting cli input for remote keymanager config

* move the input check to accounts new

* begin on requesting cli input for remote keymanager config

* define wallet v2

* create wallet most logic done

* init remote wallet

* create wallet moving nicely

* ensure wallet create works

* reenable import export list

* further refactor

* improve handling of input wallet dir

* add all validation to cert path checks

* lint

* list test

* new wallet lint

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
2020-07-14 23:05:21 -05:00
terence tsao
fe14c5086a Fix duplicated selectV1Keymanager (#6604)
* Fix duplicated selectV1Keymanager
2020-07-15 01:05:33 +00:00
Ivan Martinez
d7bcea7906 Allow creating new accounts to be non-interactive (#6602)
* Allow accounts to be made non-interactively
* Merge branch 'master' of github.com:prysmaticlabs/prysm into make-accounts-noninteractive
* Update validator/node/node.go
* Update validator/accounts/v2/list.go
2020-07-14 23:00:58 +00:00
terence tsao
eef9a760ec Fix inconsistent pubkey formatting in logs (#6600)
* Use Trunc for pub key
* Gaz
* Merge refs/heads/master into fix-pub-key
2020-07-14 20:37:01 +00:00
Ivan Martinez
5278b75c02 E2E Improvements (#6587)
* Change long-running e2e to run minimally
* Merge branch 'master' into e2e-config-change
* Remove deposits flag
* Merge branch 'e2e-config-change' of github.com:prysmaticlabs/prysm into e2e-config-change
* Merge branch 'master' of github.com:prysmaticlabs/prysm into e2e-config-change
* Reduce secondsperslot
* Add todo
* Merge branch 'master' of github.com:prysmaticlabs/prysm into e2e-config-change
* Merge refs/heads/master into e2e-config-change
* Merge refs/heads/master into e2e-config-change
* Merge refs/heads/master into e2e-config-change
* Merge refs/heads/master into e2e-config-change
* Merge refs/heads/master into e2e-config-change
* Merge refs/heads/master into e2e-config-change
2020-07-14 18:08:17 +00:00
Victor Farazdagi
d9fd2521af Applies assertion funcs to p2p tests (#6597)
* applies assertion funcs to p2p/encoder tests
* applies assertion funcs to p2p/peers tests
* addr_factory_test + broadcaster_test updated
* connection_gater_test updated
* applies assertion funcs to p2p/service tests
* Merge branch 'master' into p2p-apply-testutils-assertions
* minor fixes
* Merge branch 'master' into p2p-apply-testutils-assertions
* Merge refs/heads/master into p2p-apply-testutils-assertions
2020-07-14 16:51:39 +00:00
terence tsao
ea32af7bf7 Update justified point for batch sync (#6594)
* Update justified points
* Add the same check to on block init sync
* Add comments
* Add test
* Gaz
* Merge branch 'master' into fix-batch-sync
* Merge refs/heads/master into fix-batch-sync
2020-07-14 16:20:25 +00:00
terence tsao
8fda48409c Remove batch blocks save at getAttPreState (#6584)
* Check if block exists in cache
* Consider init sync blocks
* Fixed test
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
* Merge refs/heads/master into get-block
2020-07-14 15:46:00 +00:00
Shay Zluf
e0c803abfc Fast list validators (#6580)
* Fast list validators
* fix tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fast_list_validators
* add small test
* Merge branch 'master' into fast_list_validators
* remove unneeded fatcher
* Merge branch 'fast_list_validators' of github.com:prysmaticlabs/prysm into fast_list_validators
* nishant feedback
* package name
2020-07-14 12:21:55 +00:00
Preston Van Loon
b099cab9b1 automaxprocs: Log error to DEBUG instead of panic (#6592)
* Log error to DEBUG instead of panic. Fixes #6591
* Merge branch 'master' into fix-6591
2020-07-14 01:51:07 +00:00
Ivan Martinez
52e9155df3 Change validator accounts-v2 to validator wallet-v2 accounts (#6589)
* Change `validator accounts-v2` to `validator wallet-v2 accounts-v2

* Change to accounts

* Fix cmd

* Rename cmd.go to cmd_accounts.go
2020-07-13 19:58:06 -05:00
Preston Van Loon
774b4b7eef SubmitAggregateAndProof now prefers its own validator attestations (#6566)
* SubmitAggregateAndProof now prefers its own validator attestations
* only do aggregate bits count comparsion when best also contains the validator index
* gofmt
* better test
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* @terencechain feedback
* Merge refs/heads/master into prefer-own-attestation
* update comment
* Merge branch 'prefer-own-attestation' of github.com:prysmaticlabs/prysm into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
* Merge refs/heads/master into prefer-own-attestation
2020-07-13 22:02:01 +00:00
Ivan Martinez
cd2ea868ff Direct Keymanager: Add Export and Import commands (#6528)
* add in configs
* ask for enable accounts v2
* begin integration of v2 keymanager
* refactor wallet opening
* include significant refactoring of how opening a wallet works, making it easy to include at runtime
* ensure build with keymanager v2
* further improving runtime integration
* default pass paths
* finally running v2 at runtime
* import spacing
* Merge branch 'master' into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Get started on export and import commands
* Work more on import
* Complete functionality
* Merge branch 'master' of github.com:prysmaticlabs/prysm into accounts-import
* Undo
* Merge branch 'master' of github.com:prysmaticlabs/prysm into accounts-import
* cleanup
* Extract code to functions
* Merge branch 'master' of github.com:prysmaticlabs/prysm into accounts-import
* Add comments
* Fix ocmments
* Improvements
* fix
* Merge branch 'master' of github.com:prysmaticlabs/prysm into accounts-import
* Remove GetSigningKeyForAccount
* Progress
* Fix build
* Fix name
* Merge branch 'master' into accounts-import
* Add logging
* Merge branch 'accounts-import' of github.com:prysmaticlabs/prysm into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
* Merge refs/heads/master into accounts-import
2020-07-13 21:37:18 +00:00
terence tsao
2bbae15194 Handle roughtime response error (#6586)
* Handle roughtime response error
* Update shared/roughtime/roughtime.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Merge branch 'master' into fix-roughtime-logs
* Update shared/roughtime/roughtime.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/master into fix-roughtime-logs
* Merge refs/heads/master into fix-roughtime-logs
* Merge refs/heads/master into fix-roughtime-logs
2020-07-13 21:00:43 +00:00
terence tsao
18f28e2840 VerifyBlkDescendant - fixed a nil return bug and added a test (#6553)
* Refactor verifyBlkDescendant to be public and omit the slot argument, which was only used for error messages
* impl in mock
* gofmt
* Merge refs/heads/master into refactor-verifyBlkDescendant-signature
* Better errors
* Tests. Yay!
* Comments
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Fixed receive blck test
* Merge branch 'test-blk-des' of github.com:prysmaticlabs/prysm into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Ensure finalized root not zeros
* Merge branch 'test-blk-des' of github.com:prysmaticlabs/prysm into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
* Ensure non zero hashes when compare
* Merge branch 'test-blk-des' of github.com:prysmaticlabs/prysm into test-blk-des
* Merge refs/heads/master into test-blk-des
* Merge refs/heads/master into test-blk-des
2020-07-13 20:14:36 +00:00
Nishant Das
27577bc324 QSP 32: Add Appropriate Stream Deadlines for RPC Requests (#6583)
* add no deadlines
* Merge branch 'master' into fixDeadlines
* nogo
* Merge refs/heads/master into fixDeadlines
* Merge refs/heads/master into fixDeadlines
2020-07-13 19:40:12 +00:00
Nishant Das
79fbaaea0b QSP18: Add Varint Header Validation (#6577)
* add header validation

* Update beacon-chain/p2p/encoder/varint_test.go

* Update beacon-chain/p2p/encoder/varint_test.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-07-13 14:02:03 -05:00
Victor Farazdagi
d1e754f011 Fixes display issue in testutils/assert (#6585)
* fixes minor display issue in testutils/assert
2020-07-13 17:20:18 +00:00
Victor Farazdagi
77d1a6c698 Adds testutils/assert and testutils/require (#6563)
* testutils/assert

* adds assertion tb mock

* testutil/require

* gazelle

* comment public types

* set TestOnly attribute

* fixes package name

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-13 10:19:52 -05:00
Nishant Das
f2b4f91419 save blocks (#6578) 2020-07-13 06:33:45 -07:00
Justin
ec800bac7c Remove redundant check in exit.go (#6559)
* Remove redundant check in exit.go

The check `exit.Exit.ValidatorIndex >= uint64(beaconState.NumValidators())` is done in `beaconState.ValidatorAtIndexReadOnly(exit.Exit.ValidatorIndex)`.
* Merge branch 'master' into patch-1
* Merge branch 'master' into patch-1
* Merge branch 'master' into patch-1
* Merge branch 'master' into patch-1
* Merge branch 'master' into patch-1
2020-07-13 09:36:40 +00:00
Nishant Das
63cb99b359 add logs (#6575) 2020-07-12 22:36:03 -07:00
Nishant Das
b5bd1260d0 Clean Up P2P Service (#6574)
* clean up
* clean up
* gaz
* preston's review
* preston's review
* Merge refs/heads/master into CleanUpP2P
2020-07-13 04:16:24 +00:00
terence tsao
62df4995e6 Clean up block chain pkg initial sync (#6562) 2020-07-12 20:44:06 -07:00
Victor Farazdagi
c35bdf2649 Refactors calls to deprecated libp2p methods (#6554)
* refactors calls to deprecated IDB58Decode()
* Merge branch 'master' into p2p-refactor-deprecated
* updated packages
* gazelle
* mod tidy
* refactors publish()/subscribe() deprecated methods
* gofmt
* test update join/leave topic methods
* re-arrange imports
* Merge branch 'master' into p2p-refactor-deprecated
* Merge refs/heads/master into p2p-refactor-deprecated
2020-07-13 02:28:40 +00:00
Nishant Das
d4c3546434 Validate RPC Topics Before Sending Requests (#6558)
* clean up

* fix panic

* add test mapping

* add schema version change

* fix test

* fix another test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-13 09:20:53 +08:00
Ivan Martinez
10c0d5b569 Remove unused functions in validator DB (#6557)
* Remove unused functions in validator DB
* Iface
* Merge branch 'master' into reomve-unused-val-db
* Merge branch 'master' into reomve-unused-val-db
* Merge refs/heads/master into reomve-unused-val-db
2020-07-11 17:23:30 +00:00
Ivan Martinez
18c00ab25d Add BoltTimeout to IO config (#6555)
* Make bolt timeout a config value
* Merge refs/heads/master into best-practices0timeout
* Merge refs/heads/master into best-practices0timeout
* Merge refs/heads/master into best-practices0timeout
2020-07-11 16:43:26 +00:00
Nishant Das
b82defddb2 add timeouts (#6560) 2020-07-11 08:18:25 -07:00
Preston Van Loon
fa85d93a19 Verify roughtime results before accepting time offset (#6556)
* Verify roughtime results before accepting time offset
2020-07-11 04:42:26 +00:00
Preston Van Loon
1f35384578 Reject a block which its parent is not part of the finalized chain (#6549)
* Reject a block which its parent is not part of the finalized chain
* Refactor verifyBlkDescendant to be public and omit the slot argument, which was only used for error messages
* Merge branch 'refactor-verifyBlkDescendant-signature' into reject-bad-block
* fix
* impl in mock
* impl in mock
* gofmt
* Merge refs/heads/master into refactor-verifyBlkDescendant-signature
* Merge branch 'refactor-verifyBlkDescendant-signature' into reject-bad-block
* fix test
* add test
* Merge branch 'refactor-verifyBlkDescendant-signature' into reject-bad-block
* gofmt
* Merge branch 'master' of github.com:prysmaticlabs/prysm into reject-bad-block
* move up in the validation pipeline, @terencechain offline feedback
* Merge refs/heads/master into reject-bad-block
2020-07-11 03:57:42 +00:00
Preston Van Loon
c9ca5857f8 Avoid automaxprocs default logger to printf (#6524)
* Avoid automaxprocs default logger to printf
* Merge branch 'master' into maxprocs
* gofmt, goimports
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* gazelle for docker images
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
* fix docker
* Merge refs/heads/master into maxprocs
* Merge refs/heads/master into maxprocs
2020-07-11 00:57:43 +00:00
Preston Van Loon
6c7965e82a Refactor verifyBlkDescendant to be public in chainservice API (#6552)
* Refactor verifyBlkDescendant to be public and omit the slot argument, which was only used for error messages
* impl in mock
* gofmt
* Merge refs/heads/master into refactor-verifyBlkDescendant-signature
* fix test
2020-07-11 00:16:52 +00:00
Preston Van Loon
29317ca8da Attestation cache: check bitlist length before checking contains (#6551)
* Attestation cache: check bitlist length before checking contains
2020-07-10 21:05:03 +00:00
Preston Van Loon
dbc9686d15 Add roughtime offset histogram metric, log on large offsets (#6546)
* Add roughtime_offset_nsec metric. Log a warning if offset is greater than 2 seconds
* gofmt
* use math.abs, add help text
* gofmt
2020-07-10 17:07:49 +00:00
Nishant Das
cc8b3e349d Save Boundary States (#6542) 2020-07-10 09:00:41 -07:00
Raul Jordan
2c9474ab7f Remote Keymanager: Proto Definitions and Basic Client Implementation (#6526)
* begin on the proto definitions
* define remote signer service protos
* basic implementation
* remote keymanager docs
* finalize remote client doc
* amend response
* fix proto defs
* test new and begin test sign
* test sign done
* Merge branch 'master' into remote-keymanager-v2
* remote oneof
* rename
* Merge branch 'remote-keymanager-v2' of github.com:prysmaticlabs/prysm into remote-keymanager-v2
* fix build
* Merge refs/heads/master into remote-keymanager-v2
* viz
* Merge branch 'remote-keymanager-v2' of github.com:prysmaticlabs/prysm into remote-keymanager-v2
* Merge refs/heads/master into remote-keymanager-v2
* Merge refs/heads/master into remote-keymanager-v2
* Update validator/keymanager/v2/remote/remote_test.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
* Update validator/accounts/v2/wallet.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
* fmt
2020-07-10 05:49:56 +00:00
terence tsao
ac79819077 Fix genesis validator count (#6540)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-09 19:54:24 -05:00
terence tsao
d54cefbe42 Part 1 of blockchain pkg clean up (#6537)
* Fix span names

* Clean up on block func

* Add updateFinalized helper

* Deprecate ReceiveBlockNoPubsub for ReceiveBlock

* Proposer to broadcast block

* Update migrate interface

* Replace ReceiveBlock for all

* Go fmt
2020-07-09 18:50:48 -05:00
rkapka
f7088e037c Finalized deposits cache (#6391)
* Renamed beforeBlk to untilBlk
* finalized deposits cache logic
* Merge branch 'master' into deposit-trie-cache

# Conflicts:
#	beacon-chain/blockchain/process_block.go
* simplified returning of finalized deposits
* added comment to FinalizedDeposits struct
* fixes after code review
* Merge branch 'master' into deposit-trie-cache
* fixed variable declaration
* renamed deposit cache test file
* fixed type casting
* compilation error fix
* deposit cache tests
* proposer test
* Merge branch 'master' into deposit-trie-cache
* added missing methods to interop beacon-chain service
* gofmt
* Merge branch 'master' into deposit-trie-cache
* gazelle
* cache deposit with eth1DepositIndex
* Merge branch 'master' into deposit-trie-cache
* fixed MerkleTrieIndex name
* Merge branch 'master' into deposit-trie-cache
* Merge branch 'master' into deposit-trie-cache
* Merge branch 'master' into deposit-trie-cache
* code review adjustments
* feature flag
* Merge branch 'master' into deposit-trie-cache

# Conflicts:
#	beacon-chain/cache/depositcache/pending_deposits.go
#	shared/featureconfig/config.go
#	shared/featureconfig/flags.go
* merge fix
* gazelle
* Merge branch 'master' into deposit-trie-cache
* return a copy of deposits trie from the cache
* move more logic under feature flag
* Merge branch 'master' into deposit-trie-cache
* added missing beacon chain flag
* Merge branch 'master' into deposit-trie-cache
* use helper function for trie copying
* Merge branch 'master' into deposit-trie-cache
* Merge branch 'master' into deposit-trie-cache
* Merge branch 'master' into deposit-trie-cache
* Merge branch 'master' into deposit-trie-cache
* Merge branch 'master' into deposit-trie-cache
2020-07-09 20:24:40 +00:00
Ivan Martinez
b052ab7087 Make E2E less flaky (#6536) 2020-07-09 14:08:21 -05:00
Ivan Martinez
322998f7f1 Move subnet topics to global vars (#6525)
* Deduplicate subnet topic definitions
* Move topics to global file
* Gaz
* Merge branch 'master' into move-topics
* Fix
* Merge refs/heads/master into move-topics
* Bazel
* Merge branch 'move-topics' of github.com:prysmaticlabs/prysm into move-topics
* Fix tests
* Fix
* Undo e2e changes
* Revert "Undo e2e changes"

This reverts commit 3037bb3590.
* Fix
* Fix
* Merge refs/heads/master into move-topics
* Merge refs/heads/master into move-topics
* Merge refs/heads/master into move-topics
* Comments
* Merge refs/heads/master into move-topics
* Merge refs/heads/master into move-topics
2020-07-09 17:38:15 +00:00
terence tsao
47cbfbf437 Remove participation link when list accounts (#6535)
* Remove url
* Merge refs/heads/master into rm-link
2020-07-09 16:50:19 +00:00
Raul Jordan
15d660d8eb Direct Keymanager: Proper Keystore.json Formatting (#6527)
* ensure keystore file has all fields
* fix tests
* fix build
* Merge branch 'master' into full-keystore-json
* define wallet.CanUnlockAccounts() to determine secret keys cache
initialization
* Merge branch 'full-keystore-json' of github.com:prysmaticlabs/prysm into full-keystore-json
* add can unlock accounts items
* Merge refs/heads/master into full-keystore-json
* Merge refs/heads/master into full-keystore-json
* Merge refs/heads/master into full-keystore-json
* Merge refs/heads/master into full-keystore-json
2020-07-09 16:24:06 +00:00
Raul Jordan
e3de674c77 Direct Keymanager: Proper Keystore.json Formatting (#6527)
* ensure keystore file has all fields
* fix tests
* fix build
* Merge branch 'master' into full-keystore-json
* define wallet.CanUnlockAccounts() to determine secret keys cache
initialization
* Merge branch 'full-keystore-json' of github.com:prysmaticlabs/prysm into full-keystore-json
* add can unlock accounts items
* Merge refs/heads/master into full-keystore-json
* Merge refs/heads/master into full-keystore-json
* Merge refs/heads/master into full-keystore-json
* Merge refs/heads/master into full-keystore-json
2020-07-09 16:23:53 +00:00
Preston Van Loon
fd80f73286 Improve make() capacity allocations (#6517)
* attestationutil.AttestingIndices: Minor improvement on indices array allocation
* progress
* more progress on makes
* progress
* more progress
* Merge branch 'master' of github.com:prysmaticlabs/prysm into memory1
* gaz
* fmt and imports
* Merge branch 'master' into memory2
* Min()
* remove spaces
* Merge branch 'master' of github.com:prysmaticlabs/prysm into memory2
* revert beacon-chain/operations/attestations/kv/block.go
* partially revert beacon-chain/operations/attestations/kv/aggregated.go
* Merge branch 'master' into memory2
* Merge branch 'master' into memory2
2020-07-09 15:50:58 +00:00
Nishant Das
c804347fc4 add fix and test (#6533)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-09 09:46:35 -05:00
Jim McDonald
b00c235586 Add separate permission for directories. (#6532) 2020-07-09 22:05:43 +08:00
Preston Van Loon
c2deab8948 State: use a constant for field count (#6513)
* State: use a constant for field count
* one more field count for alloc
* one more field count for alloc
* Merge branch 'master' into field-const-21
* Merge branch 'master' into field-const-21
* Merge branch 'master' into field-const-21
* Merge branch 'master' into field-const-21
2020-07-09 03:37:08 +00:00
terence tsao
8da0246702 Close buf writer in event of an error (#6523)
* Close buf writer in event of an error
* Merge refs/heads/master into close-bufwriter
* Merge refs/heads/master into close-bufwriter
2020-07-08 20:03:03 +00:00
Raul Jordan
132ad5beb8 Implement Accounts-v2 List: Direct Keymanager (#6510)
* begin list accounts impl
* colorize
* show deposit data
* separate responsibility
* comprehensive test for list complete
* gaz viz
* print account creation timestamp
* handle errs
* ask for wallet and pass dir
* Merge refs/heads/master into implement-v2-list
2020-07-08 19:21:54 +00:00
Ivan Martinez
ddf494f7b7 Use same permissions for all files in Prysm (#6522)
* Unify all perm prysm wide

* Gaz

* Imports
2020-07-08 12:30:22 -05:00
Victor Farazdagi
af4dfd4c36 Tiny optimization in state refs lock/unlock (#6520)
* tiny optimization in state refs count
2020-07-08 12:53:36 +00:00
Preston Van Loon
f2f2677070 attestationutil.AttestingIndices: Minor improvement on indices array allocation (#6508)
* attestationutil.AttestingIndices: Minor improvement on indices array allocation
* Merge branch 'master' of github.com:prysmaticlabs/prysm into HEAD
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
* Merge refs/heads/master into memory1
2020-07-08 09:57:50 +00:00
Preston Van Loon
a279f18461 Change from int64 to int for all flags so they load properly from config file. (#6498)
* Change from int64 to int for monitoring port so that the monitoring port is correctly ready from config file.
* Merge branch 'master' into fix-monitoring-port
* Merge branch 'master' into fix-monitoring-port
* Merge branch 'master' into fix-monitoring-port
* replace all other usages of int64 flag. @nisdas feedback
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-monitoring-port
* Merge branch 'master' into fix-monitoring-port
* Merge branch 'master' into fix-monitoring-port
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-monitoring-port
* revert tools/sendDepositTx
* fix build
* Merge branch 'master' into fix-monitoring-port
* Merge branch 'master' into fix-monitoring-port
* Merge branch 'master' into fix-monitoring-port
2020-07-08 08:21:06 +00:00
Preston Van Loon
c1ccadae55 Delete unused helpers.AttestingIndices (#6509)
* Delete unused helpers.AttestingIndices
* Merge branch 'master' into rm-AttestingIndices
* Merge branch 'master' into rm-AttestingIndices
* Merge branch 'master' into rm-AttestingIndices
* Merge branch 'master' into rm-AttestingIndices
2020-07-08 07:30:29 +00:00
Preston Van Loon
a02553815f Allocate the appropriate memory for retrieveIndicesFromBitfield (#6507)
* Allocate the appropriate memory for retrieveIndicesFromBitfield
* Merge refs/heads/master into memory0
* Merge refs/heads/master into memory0
* Merge refs/heads/master into memory0
* Merge refs/heads/master into memory0
* Merge refs/heads/master into memory0
* Merge refs/heads/master into memory0
* Merge refs/heads/master into memory0
2020-07-08 05:47:26 +00:00
Raul Jordan
fd9003f822 Integrate Accounts v2 Keymanager Into Validator Client (#6489)
* add in configs
* ask for enable accounts v2
* begin integration of v2 keymanager
* refactor wallet opening
* include significant refactoring of how opening a wallet works, making it easy to include at runtime
* ensure build with keymanager v2
* further improving runtime integration
* default pass paths
* finally running v2 at runtime
* import spacing
* Merge branch 'master' into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* confs
* rem e2e val flag
* Merge branch 'master' into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
* Merge refs/heads/master into v2-accounts-feature
2020-07-08 05:01:09 +00:00
terence tsao
fe13f1f856 Add init-sync-verbose feature flag (#6515)
* Add flag
* Use flag
* Merge refs/heads/master into init-sync-verbose
* Merge refs/heads/master into init-sync-verbose
* Merge refs/heads/master into init-sync-verbose
* Merge refs/heads/master into init-sync-verbose
* Merge refs/heads/master into init-sync-verbose
2020-07-08 04:19:58 +00:00
Nishant Das
074e3c9aa7 Use Custom Block Hashing Method (#6501)
* blockroot
* gaz
* Merge refs/heads/master into useCustomMethod
* Merge refs/heads/master into useCustomMethod
* Merge refs/heads/master into useCustomMethod
* Merge refs/heads/master into useCustomMethod
* Merge refs/heads/master into useCustomMethod
* Merge refs/heads/master into useCustomMethod
* Merge refs/heads/master into useCustomMethod
* Merge refs/heads/master into useCustomMethod
2020-07-08 03:53:16 +00:00
terence tsao
d42d685f78 Update verifyBlkPreState to verify only (#6506)
* Verify should not return the state
* Update tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into refactor
* Sync with master
* Merge refs/heads/master into refactor
* Fixed error msgs. Thanks @rauljordan
* Merge branch 'master' of github.com:prysmaticlabs/prysm into refactor
* Merge branch 'refactor' of github.com:prysmaticlabs/prysm into refactor
* Merge refs/heads/master into refactor
* Merge refs/heads/master into refactor
* Merge refs/heads/master into refactor
2020-07-08 02:54:55 +00:00
Preston Van Loon
1067800430 p2p.AddConnectionHandler: Remove unused arg for goodbyeFunc (#6511)
* p2p.AddConnectionHandler: Remove unused arg for goodbyeFunc
* accidental rename reqFunc
* update test
* Merge branch 'master' into rm-unused-param
* Merge branch 'master' into rm-unused-param
2020-07-08 02:04:15 +00:00
terence tsao
d53ab16004 Move skip-regen-historical-states to deprecated (#6512)
* Remove unused test
* Move flag to be deprecated
* Remove usages
* Update BUILD.bazel
* Merge refs/heads/master into rm-skip-stategen-usages
2020-07-08 00:15:45 +00:00
Preston Van Loon
90b8b76ae8 Remove unused EpochAttestationsRoot method (#6514)
* Remove unused EpochAttestationsRoot method
2020-07-07 23:39:11 +00:00
dv8silencer
c77296ff82 Show overall validator results in addition to epoch specific results (#6492)
* Add aggregate stats struct to validator struct.  Log aggregate voting summary
from beginning of node startup.
* Refactoring out to function UpdateLogAggregateStats which updates and logs aggregate statistics
* Changes to spelling.  More refactoring so that the rest of aggregate stats are moved to UpdateLogAggregateStats
* Bugfix - moved startBalance initialization out of if.
* Remove a print debug.  Spelling adjustment.
* Minor refactoring/grammar changes
* Renaming variables for consistency.
* Address linter feedback:  omit 2nd value from range over map as values were not being used.
* Address feedback from PR re comments.

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Addressing feedback from terencechain in PR. (name changes)
* Addressing feedback from terencechain in PR.
* Create test for UpdateLogAggregateStats()
* Changed comment regarding "numberOfEpochs" log
* go fmt metrics_test.go
* bazel run //:gazelle -- fix
* fix typos
* Improved the code to detect the last iteration of the range responses loop
* Merge branch 'master' into tempIssue4987
* For both previous Epoch and total runtime statistics, do not count non-included attestations for "correctly" statistics.
* Update wording in since-launch logging

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Store first logged epoch in startEpoch and appropriately adjust calculations.  Initialize startEpoch to ^uint64(0).
* Merge branch 'master' into tempIssue4987
* Update validator/client/metrics.go
* Update validator/client/metrics.go
* Update validator/client/validator.go
* Update validator/client/metrics_test.go
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
* Merge branch 'master' into tempIssue4987
2020-07-07 19:23:56 +00:00
Shay Zluf
87c18d4e0d Slasher readiness status response (#6504)
* Slasher readiness status response
* add comments
* Merge refs/heads/master into slasher_status
* Merge refs/heads/master into slasher_status
2020-07-07 17:11:07 +00:00
Ivan Martinez
d9fea7cb8c [QSP] Deduplicate functions for audit best practices (#6476)
* Deduplicate DB functions and getters

* Rename function

* Reduce to prestons suggestions

* Fix bug

* Fix

* Start changing state db funcs

* Fix tests

* Change return

* Add checks

* Fix test

* Fix

* Nishant comment

* Fix

* Fix

* Fix

* Fix

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-07 11:29:25 -05:00
Nishant Das
b868dfa481 Save Archived State (#6503) 2020-07-07 08:04:55 -07:00
Preston Van Loon
46b82eb15d Sync: Verify all block and attestations signatures on finalized blocks by default (#6499)
* Make verifying all signatures the default operation
* Merge branch 'master' into flip-verify-all
* Merge branch 'master' into flip-verify-all
* Merge branch 'master' into flip-verify-all
* Merge branch 'master' into flip-verify-all
2020-07-07 05:13:45 +00:00
Nishant Das
64fa474434 Batch Verify Blocks (#6469)
* add everything so far
* checkpoint progress
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
* fix
* checkpoint
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
* checkpoint again
* checkpoint again
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
* commenting
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
* bls cleanup
* revert this back
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
* revert core changes
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
* add flag
* add test
* add one more test
* clean up
* comment
* lint
* terence's review
* Merge refs/heads/master into fastBLS
* Merge refs/heads/master into fastBLS
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
* Merge refs/heads/master into fastBLS
* remove additional method
* Merge branch 'fastBLS' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
* fix
* Merge refs/heads/master into fastBLS
* copy
* Merge branch 'fastBLS' of https://github.com/prysmaticlabs/geth-sharding into fastBLS
2020-07-07 04:16:12 +00:00
Shay Zluf
8ddfde41e3 Historical detection fix (#6455)
* Historical detection before realtime detection

* comment fixes

* remove logs

* remove logs

* remove logs

* gaz

* handle underflow

* add regressiion test

* update test name

* gaz

* gofmt

* fix comment

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-07-07 05:57:40 +03:00
terence tsao
7f741e48e0 Cleanup process block/operation names (#6500) 2020-07-06 18:24:30 -07:00
Preston Van Loon
e96e1f0569 Add a placeholder constant for ignoring cancelled subscription errors from libp2p pubsub. (#6496)
* Add a placeholder constant for ignoring cancelled subscription errors
from libp2p pubsub.

This change temporarily resolves
https://github.com/prysmaticlabs/prysm/issues/6449.

This change should be revisited after
https://github.com/libp2p/go-libp2p-pubsub/pull/356 merges and the prysm
libp2p pubsub dependency is updated.
* Merge branch 'master' into issue-6449
* Merge branch 'master' into issue-6449
* Merge branch 'master' into issue-6449
2020-07-06 23:55:55 +00:00
terence tsao
1a6c55c637 Split block_operations.go into smaller files (#6495) 2020-07-06 15:27:42 -07:00
Jim McDonald
7bb0ee78af Update beacon state locks (#6326)
* Rationalise state locking
* Rationalise state locking
* Merge branch 'state-locks' of github.com:mcdee/prysm into state-locks
* Merge branch 'master' into state-locks
* Add feature flag
* Merge
* Merge branch 'master' into state-locks
* Merge branch 'master' into state-locks
* Update locks
* Merge branch 'master' into state-locks
* Gazelle
* Tidy-ups
* Merge branch 'master' into state-locks
* Remove commentary to a docs.go file for better presentation on godocs
* Add newBeaconStateLocks as a --dev flag
* gofmt
* Merge branch 'master' into state-locks
2020-07-06 20:52:53 +00:00
Preston Van Loon
005a9dde48 CI: Remove GCP remote cache (#6497)
* Remove GCP remote cache as it has been sunset on GCP
2020-07-06 19:25:35 +00:00
terence tsao
def7b602e3 Hot states use no DB (#6488)
* Add cache to service struct
* Update hot getters/setters to use cache
* Update migration
* Update other services to adapt
* Fix initial sync get state
* Update getter related tests
* Update hot related tests
* Update migrate related tests
* New awesome tests for migration
* Clean up rest of the tests
* Merge refs/heads/master into hot-state-no-db
* Fix block chain head tests
* Fix block chain processor tests
* Fixed RPC tests
* Update cold getter and test
* Merge branch 'hot-state-no-db' of github.com:prysmaticlabs/prysm into hot-state-no-db
* Fix sync tests
* Short cut if state is already in DB
* Remove uneeded saves
* Update beacon-chain/state/stategen/hot_test.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Update beacon-chain/state/stategen/getter_test.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Update beacon-chain/state/stategen/getter_test.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Update beacon-chain/state/stategen/service.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Update beacon-chain/state/stategen/setter_test.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Preston's feedback
* Merge branch 'hot-state-no-db' of github.com:prysmaticlabs/prysm into hot-state-no-db
* Return a copy of cache states
* Remove hot state caches check in StateByRoot
* Merge branch 'hot-state-no-db' of github.com:prysmaticlabs/prysm into hot-state-no-db
* Merge refs/heads/master into hot-state-no-db
* Raul's feedback
* Merge branch 'hot-state-no-db' of github.com:prysmaticlabs/prysm into hot-state-no-db
2020-07-06 17:22:12 +00:00
Nishant Das
fa3da9a6a2 Add In New Core Methods for Batch Verify (#6482)
* add in new core methods

* clean up

* add verification method

* add tests

* add 1 more test

* lint

* Update beacon-chain/core/blocks/block_operations.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* Update beacon-chain/core/blocks/block_operations.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* Update beacon-chain/core/state/transition.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* terences review

* Update beacon-chain/core/state/transition.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* fmt

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-07-06 11:09:29 +08:00
Ivan Martinez
359b9bef49 Merge separated local slashing protection flags (#6487)
* Merge split-up local protection flags

* Fix deprecated flags

* Fix text
2020-07-03 21:01:54 -05:00
Raul Jordan
d447bb6458 Direct Keymanager: Implement Sign (#6477)
* implement keymanager proto

* utilize proto message and properly comment

* add in godoc

* doc

* add in doc

* sign implementation done

* add documentation for direct keymanager and add lock to signing

* sign method tests

* update godoc

* concrete sign

* fix build

* proper iface
2020-07-03 18:00:02 -05:00
Raul Jordan
8c258278d0 Direct Keymanager: Implement FetchValidatingPublicKeys() (#6475)
* begin on fetch direct
* fetch validating public keys impl
* test for fetch validating keys
* fetch validating public keys done
* helper function and benchmark
* rename package
* viz
* Update validator/accounts/v2/testing/BUILD.bazel

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* gaz
* add lock
* comment
* Merge refs/heads/master into fetch-direct-keys
2020-07-03 20:26:00 +00:00
Ivan Martinez
f0fcebccc4 Move slashing protection code to separate files for proposing and attesting (#6406)
* Get started on cleaning up slashing protection
* Merge branch 'master' of github.com:prysmaticlabs/prysm into cleanup-protection
* Move protection functions to own files
* Lint
* Merge branch 'master' of github.com:prysmaticlabs/prysm into cleanup-protection
* Begin adding test for proposal protection
* Merge branch 'master' of github.com:prysmaticlabs/prysm into cleanup-protection
* Fix build
* Fix tests
* Fix tst
* Fix tests
* Fix proposal tests
* Merge branch 'master' into cleanup-protection
* Merge branch 'master' into cleanup-protection
* Merge branch 'master' into cleanup-protection
* Merge branch 'master' of github.com:prysmaticlabs/prysm into cleanup-protection
* Reorder protections
* Change lock
* Fix test
* Merge branch 'master' into cleanup-protection
* Merge branch 'master' into cleanup-protection
* Merge branch 'master' into cleanup-protection
* Change log
* Merge branch 'cleanup-protection' of github.com:prysmaticlabs/prysm into cleanup-protection
* Merge branch 'master' into cleanup-protection
2020-07-03 19:54:42 +00:00
Raul Jordan
9d979de4ed Direct Keymanager: Implement Account Creation (#6466)
* implementation using petname and keystore
* writing new account to disk along with password
* more logic for properly writing accounts
* print out mnemonic
* save deposit data rlp
* write deposit tx and ssz deposit data to account path
* wrap up account creation
* fix prompt
* generate deposit tx
* direct account creation test
* fix up formatting
* lint
* match formatting
* more sustainable approach towards unmarshaling config file
* resolve feedback
* fix broken import
* comprehensive tests for create account
* tests pass
* Merge branch 'master' into direct-keys
* tidy
* Merge branch 'direct-keys' of github.com:prysmaticlabs/prysm into direct-keys
* Merge refs/heads/master into direct-keys
* gaz
* Merge branch 'direct-keys' of github.com:prysmaticlabs/prysm into direct-keys
* nondeterministic names
* comment
* gaz
* better error wrap
* Merge refs/heads/master into direct-keys
* docker deps
* Merge branch 'direct-keys' of github.com:prysmaticlabs/prysm into direct-keys
* Merge refs/heads/master into direct-keys
* Merge refs/heads/master into direct-keys
* Merge refs/heads/master into direct-keys
* Merge refs/heads/master into direct-keys
* Merge refs/heads/master into direct-keys
* Merge refs/heads/master into direct-keys
* Merge refs/heads/master into direct-keys
* Merge refs/heads/master into direct-keys
* Merge refs/heads/master into direct-keys
* ivan feedback
* Merge refs/heads/master into direct-keys
* Update validator/accounts/v2/wallet.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* fixed tests and comments
* Merge refs/heads/master into direct-keys
2020-07-03 18:49:16 +00:00
terence tsao
8bb5532377 Epoch boundary cache (#6486)
* Add epoch boundary state cache
* Clean up epoch boundary state cache
* Starting tests
* More tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into epoch-boundary-cache
* Merge refs/heads/master into epoch-boundary-cache
2020-07-03 17:29:30 +00:00
Victor Farazdagi
688f0d7114 Refactors attestation pool pruning (#6485) 2020-07-03 09:43:56 -07:00
Ivan Martinez
c69b3f568e Move hard-coded constants to global consts (#6467)
* Move hard-coded constants to global consts
* Fixes
* Merge branch 'master' into remove-hard-constants
* Merge refs/heads/master into remove-hard-constants
* Merge refs/heads/master into remove-hard-constants
* Merge refs/heads/master into remove-hard-constants
* Merge refs/heads/master into remove-hard-constants
* Comments
* Merge refs/heads/master into remove-hard-constants
* Merge refs/heads/master into remove-hard-constants
* Merge refs/heads/master into remove-hard-constants
* Merge refs/heads/master into remove-hard-constants
* Merge refs/heads/master into remove-hard-constants
* Merge branch 'master' of github.com:prysmaticlabs/prysm into remove-hard-constants
2020-07-03 15:25:32 +00:00
Victor Farazdagi
d1f1628478 Restores att-aggregation benchmarks (#6484)
* restores att-aggregation benchmarks
2020-07-03 14:37:54 +00:00
Nishant Das
7896e087e5 Add in Better Logging for Requests (#6483)
* add in better logging
* gaz
* last one
* mess about
* check strings
* fix
2020-07-03 10:08:45 +00:00
Nishant Das
ac9bc5d98b Reset Streams at the End of the Request (#6481)
* close all incoming streams

* use proper helper

* shift to debug

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-03 16:21:18 +08:00
Nishant Das
353229d50a Add New Secure Batch Signature Verification Method (#6479)
* add more tests
* gaz
* Merge refs/heads/master into addBLSMethods
* Merge refs/heads/master into addBLSMethods
* Merge refs/heads/master into addBLSMethods
* Merge refs/heads/master into addBLSMethods
2020-07-03 07:38:13 +00:00
terence tsao
d62e989a67 Minor clean up on state gen package (#6480)
* Remove unused fields and function
* Rename splitInfo to finalizedInfo
* Merge branch 'master' into stategen-cleanup
* Fmt
* Merge branch 'stategen-cleanup' of github.com:prysmaticlabs/prysm into stategen-cleanup
* Merge refs/heads/master into stategen-cleanup
2020-07-03 06:33:58 +00:00
Preston Van Loon
6b9d9e5d3a Add a few test cases to ReceiveBlockNoPubsub with race detection (#6298)
* Add a few test cases to ReceiveBlockNoPubsub with race detection, fix data race in state
* Expose voluntary exits included API. More race condition fixes in state. More tests
* add tests to norace as well for coverage
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-test-coverage-on-receive-block
* PR feedback
* Fixed can't save head in DB by:
1.) Remove new state mgmt condition in SaveHeadBlockRoot
2.) Reuse state summary cache between db and service
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-test-coverage-on-receive-block
* passing tests
* gofmt and goimports
* Merge branch 'master' of github.com:prysmaticlabs/prysm into add-test-coverage-on-receive-block
* lint
* move import and goimport again
* move import and goimport again
* Merge refs/heads/master into add-test-coverage-on-receive-block
* Merge refs/heads/master into add-test-coverage-on-receive-block
* Add bool to selectively record events
* Merge refs/heads/master into add-test-coverage-on-receive-block
* Merge refs/heads/master into add-test-coverage-on-receive-block
* Merge refs/heads/master into add-test-coverage-on-receive-block
* Merge refs/heads/master into add-test-coverage-on-receive-block
2020-07-03 05:46:53 +00:00
dv8silencer
0d2bce8200 Improve consistency in peer connect/disconnect logging (#6409)
* Improve consistency in peer connect/disconnect logging
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Corrected capitalization.  Refactored out duplicated logic
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
* Merge branch 'master' into dv8s-iss6328
2020-07-03 04:44:57 +00:00
Raul Jordan
5b708b54d9 QSP-13 Only Allow Snappy P2P Encoding (#6415)
* enforce only snappy

* fix up tests

* replace with ssz snappy in tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-03 11:24:30 +08:00
Preston Van Loon
aa52e693ce Sync: do not remove attestations from pool on failed block processing (#6474)
* Add test and return error on failed block processing
* use atts in body
* Merge branch 'master' into p2p-potential-error-block
2020-07-02 20:24:30 +00:00
Raul Jordan
091525deb8 Revert Stream Duties (#6473)
* ensure gazelle
* fix up propose test
* build
* comment
2020-07-02 17:50:05 +00:00
Victor Farazdagi
f279cf09b8 Removes excessive concurrency from init-sync queue (#6471)
* Removes excessive concurrency from init-sync queue
* update buffer size
2020-07-02 13:06:12 +00:00
Victor Farazdagi
92c5c651f7 Refactors init-sync: queue streams blocks in batches (#6470)
* init-sync: queue streams blocks in batches
2020-07-02 11:19:07 +00:00
Raul Jordan
2d6f4ebf18 Part 1: Implement Accounts-V2 New, Wallet Creation (#6451)
* begin accounts-v2 new

* password validation

* validator accounts new with eip-2335 keystore

* select different wallet type based on enum

* clean up code significantly

* more robust code structure

* check if wallet exists

* define read and create wallet methods

* fmt

* go mod and comment

* comment

* redundant name

* satify gofmt

* add instructions with keymanager opts

* wrap up create and read wallet functionality

* prep for readiness

* doc improvements

* tests for create and read wallet

* update deps

* tidy

* visibility

* gaz

* fix up

* refactor for proper usage, with wallet and keymanager ifaces

* Update validator/flags/flags.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* import

* improve structure

* wrap up all comments

* simplify

* lint

* Update validator/accounts/v2/cmd.go

* viz check

* add interface methods as needed

* fix build

* lint

* nishant feedback

* simplify structure

* add tests for strong password check

* all feedback done

* ivan feedback

* ivan feedback

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-07-01 16:30:01 -05:00
terence tsao
8c8cc144f1 Archival RPC usages removal (#6453)
* Starting to delete archived rpc usages
* Fixed rest of the tests
* Gaz
* Merge branch 'master' into deprecate-archival-rpc
* Merge branch 'master' into deprecate-archival-rpc
* Merge refs/heads/master into deprecate-archival-rpc
* Merge refs/heads/master into deprecate-archival-rpc
* Merge refs/heads/master into deprecate-archival-rpc
2020-07-01 20:04:02 +00:00
Martin Linkhorst
aeb0b4bf75 Allow to start slasher RPC server with TLS (#6465)
* add warning if slasher server isn't using tls
* pass on tls key and cert to the slasher rpc server
* Merge branch 'master' into slasher-tls
2020-07-01 19:31:29 +00:00
Victor Farazdagi
270a64f059 QSP-BestPractice: Refactors singular/plural KV-store functions (#6462)
* updates SaveBlock
* updates DeleteAttestation
* updates DeleteState
* updates SaveAttestation
* updates SaveState
* updates SaveStateSummary
* Merge refs/heads/master into kv-refactor-singular-pl-methods
* Merge refs/heads/master into kv-refactor-singular-pl-methods
* Merge refs/heads/master into kv-refactor-singular-pl-methods
2020-07-01 18:33:05 +00:00
Preston Van Loon
165cb0d7b4 E2E: Add a check for cold state storage (#6457)
* Add a check for cold state storage
* amend comment
* gaz
* Merge branch 'master' into coldstate-e2e
* Merge refs/heads/master into coldstate-e2e
* Merge refs/heads/master into coldstate-e2e
* PR feedback
* Merge branch 'coldstate-e2e' of github.com:prysmaticlabs/prysm into coldstate-e2e
* Update endtoend/evaluators/data.go
* Merge refs/heads/master into coldstate-e2e
* Merge refs/heads/master into coldstate-e2e
* Merge refs/heads/master into coldstate-e2e
2020-07-01 17:35:05 +00:00
terence tsao
1f3d9873cd Archival service removal (#6448) 2020-07-01 10:04:06 -07:00
Victor Farazdagi
1b0cfb408e QSP-BestPractice: Refactors inline ttfb/resp time constants (#6463)
* refactors inline ttfb/resp time constants
2020-07-01 09:47:59 +00:00
terence tsao
4e180e452d Add spans to db kv's encode and decode (#6458) 2020-06-30 21:00:49 -07:00
terence tsao
8d8da76aa0 API: Fix finalization/justification slot representations (#6443)
* Fix finalized/justified slots representations
* Update tests
* Merge refs/heads/master into use-epochs
* Merge refs/heads/master into use-epochs
* Merge refs/heads/master into use-epochs
* Merge refs/heads/master into use-epochs
* Go fmt
* Merge branch 'use-epochs' of github.com:prysmaticlabs/prysm into use-epochs
* Merge refs/heads/master into use-epochs
* Merge refs/heads/master into use-epochs
* Fixed TestServer_StreamChainHead_OnHeadUpdated
* Merge branch 'use-epochs' of github.com:prysmaticlabs/prysm into use-epochs
* Merge refs/heads/master into use-epochs
2020-06-30 15:17:59 +00:00
Raul Jordan
a0c38c8d0a QSP-33 Check Max Response For All Topics (#6424)
* remove max len funcs

* fix up tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-30 09:50:28 -05:00
Nishant Das
21ead0a025 Record Peer Latency (#6456)
* add latency
* Merge branch 'master' into addLatency
* Merge refs/heads/master into addLatency
2020-06-30 03:53:14 +00:00
Preston Van Loon
98e26d1dcc Bulk verify block deposits with BLS (#6454)
* First pass at adding bulk signature verification for block deposits

* checkpoint

* some refactoring to allow for bulk deposit signature verification

* nil check

* fix goimports

* fmt

* rename ProcessPreGenesisDeposit -> ProcessPreGenesisDeposits
2020-06-29 20:52:19 -05:00
terence tsao
1f93a1f4c3 Remove unused prune old states (#6450) 2020-06-29 15:02:31 -07:00
Raul Jordan
6c7131cb54 Fix Concurrent Map Write in gRPC Client Connected Logger (#6446)
* fix up concurrent map write
* fix import
* Merge refs/heads/master into concurrent-write-fix
2020-06-29 15:52:10 +00:00
Victor Farazdagi
196f4c6222 QSP-BestPractice Refactors failover peer selection in init-sync (#6442)
* refactors failover peer selection in init-sync
* Merge refs/heads/master into init-sync-more-effective-failover
2020-06-29 15:23:04 +00:00
Ivan Martinez
e7b24323e6 Move MaxRPCPageSize flag from beacon node to shared/cmd (#6297)
* Allow other clients to set MaxRPCPageSize

* Fixes

* Remove default

* Add init

* Fix default

* Set default

* Fix

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-29 09:17:24 -05:00
Preston Van Loon
047880caf2 Change the aggregatedSlotCommitteeIDCacheLock to release the lock immediately after r/w (#6437)
* Change the aggregatedSlotCommitteeIDCacheLock to release the lock immediately after r/w
* Merge branch 'master' into better-validator-lock
* Merge branch 'master' into better-validator-lock
2020-06-29 06:14:21 +00:00
Nishant Das
2bce9c884a Add More Altona Bootnodes (#6441)
* enable noise
* add secio
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into makeNoiseDefault
* add new bootnodes
2020-06-29 04:02:20 +00:00
Nishant Das
adf9bf7094 QSP 50, QSP 51: Make Noise Default (#6440)
* enable noise

* add secio
2020-06-29 11:19:25 +08:00
Preston Van Loon
bfb6e5e4a0 Use spec attestation time verification in gRPC requests (#6429)
* Re-use attestation time verification

* lint

* fix imports

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-28 14:37:17 -07:00
Ivan Martinez
d973c00c6c Slasher detection improvements (#6432)
* Slashing fixes

* Fixess

* Change fatals to error

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-28 02:34:21 -04:00
Raul Jordan
417bb45398 Begin Scaffold of Validator Accounts V2 (#6310)
* v2 refactor
* fix up imports
* builds
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge branch 'master' into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* imports keymanager v1
* Update validator/keymanager/v1/remote.go
* Update validator/client/polling/propose.go
* Update validator/keymanager/v1/wallet.go
* fmt
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* Merge refs/heads/master into accounts-revamp-p1
* fix conf
* fix build
* gaz
2020-06-27 15:48:36 +00:00
terence tsao
2a997828a3 Audit best practice feedback - validator DB test folder (#6426)
* Refactor validators db

* Lint

* Lint

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-26 21:37:43 -05:00
Preston Van Loon
a9bbbae19a Refactor params/config to separate files for clarity (#6427)
* split mainnet/onyx/altona/e2e configs into different files
* set onyx as the default network
* lint and fix comment
* more commentary
* gofmt
* Merge branch 'master' of github.com:prysmaticlabs/prysm into onyx-config
* gofmt
2020-06-27 00:20:24 +00:00
terence tsao
43b1bcb84f Use CopyValidator for ValidatorAtIndex (#6430)
* Use CopyValidator
* Merge refs/heads/master into validator-at-index
2020-06-26 23:21:11 +00:00
Preston Van Loon
c6179307b3 Add spans for head state access (#6418)
* Add a span for HeadState access
* more spans
* Merge refs/heads/master into add-span
* Merge refs/heads/master into add-span
* Merge refs/heads/master into add-span
* Merge refs/heads/master into add-span
* Merge refs/heads/master into add-span
* Merge refs/heads/master into add-span
* Merge refs/heads/master into add-span
* Merge refs/heads/master into add-span
2020-06-26 22:52:11 +00:00
Nishant Das
5d53aa3cac Update Config for Altona (#6414) 2020-06-26 15:11:40 -07:00
Preston Van Loon
67b8a88b65 Add span for updateRecentCanonicalBlocks (#6421)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-26 15:08:53 -05:00
Preston Van Loon
3ba3133657 Cleanup validateAggregateAttTime with a better error message, more tests, and more clear inline comments (#6423)
* Add span for updateRecentCanonicalBlocks
* Cleanup validateAggregateAttTime with a better error message, more tests, and more clear inline comments
* Merge branch 'master' into cleanup-validateAggregateAttTime
* revert beacon-chain/blockchain/head.go
* Merge branch 'cleanup-validateAggregateAttTime' of github.com:prysmaticlabs/prysm into cleanup-validateAggregateAttTime
* Merge refs/heads/master into cleanup-validateAggregateAttTime
* Merge refs/heads/master into cleanup-validateAggregateAttTime
2020-06-26 19:36:44 +00:00
terence tsao
01b97ffd5e Fix ListValidators retrieval for new state (#6417)
* Retrieve the correct state for new state
* Test
* Gaz
* Merge branch 'master' into fix-list-validators
* Merge refs/heads/master into fix-list-validators
* Merge refs/heads/master into fix-list-validators
* Merge refs/heads/master into fix-list-validators
* Merge refs/heads/master into fix-list-validators
2020-06-26 19:01:46 +00:00
Preston Van Loon
886afb054c Remove duplicated randao mix copy (#6420)
* remove duplicated randao mix copy
* Merge refs/heads/master into rm-dup-copy
* Merge refs/heads/master into rm-dup-copy
* Merge refs/heads/master into rm-dup-copy
2020-06-26 18:27:48 +00:00
Nishant Das
98757e759c Update Geth (#6422)
* update geth
* Merge refs/heads/master into removeSlowdown
2020-06-26 17:59:02 +00:00
Raul Jordan
001547f215 QSP-55 Remove Support for Other Pubsub Protocols (#6419)
* remove nongossip protocols
* Merge refs/heads/master into remove-other-protocols
2020-06-26 17:33:18 +00:00
Nishant Das
f1c0b2e0da Fix Invalid SSZ in Block Roots RPC Request (#6405)
* fix block roots error
* remove comment
* fix
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fixBlockRootsError
* change back
* add stream deadlines
* Merge branch 'master' into fixBlockRootsError
* add todos
* Merge branch 'fixBlockRootsError' of https://github.com/prysmaticlabs/geth-sharding into fixBlockRootsError
* Update beacon-chain/sync/rpc_beacon_blocks_by_root.go

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
* gofmt
* fix test
* fix failing test
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fixBlockRootsError
* fix all
* Merge branch 'master' into fixBlockRootsError
* Merge branch 'master' into fixBlockRootsError
* Merge refs/heads/master into fixBlockRootsError
2020-06-26 17:05:04 +00:00
Raul Jordan
ab89053597 QSP-45 Add Check for No Connected Peers BestFinalized (#6402)
* no error returned
* no target root
* fix build
* Merge refs/heads/master into best-finalized
2020-06-26 16:35:12 +00:00
Raul Jordan
252f758baa QSP-9 Prevent Casting to Int if Possible (#6349)
* no cast to int

* fix up significant casting issues

* more casting

* even more casting fixes

* more casts

* fix subnets

* back to ints

* final touches

* broken test fix

* add in blocks test fix

* unskip

* revert bytes fixes

* casting fixes

* Update beacon-chain/db/kv/state.go

* Update beacon-chain/db/kv/blocks.go

* fmt

* slash:

* fix val tests

* fix up conf

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
2020-06-26 11:07:00 -05:00
Victor Farazdagi
78465e2549 QSP-6: Enforces crypto-secure PRNGs (#6401)
* adds cryptorand analyzer

* better naming

* rely on suffix

* sync/pending_* use crypto/rand

* define shared/rand

* updates fetcher

* fixes rand issue in sync package

* gofmt

* shared/rand: more docs + add exclusion nogo_config.json

* updates validator/assignments

* updates comment

* fixes remaning cases

* re-arranges comments

* fixes tests

* renames in shared/rand API

* adds simple no-panic test

* gazelle

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-26 09:58:47 -05:00
Nishant Das
73f3a653bf Clean Up Dead Peers (#6413)
* clean up dead peers
* Merge refs/heads/master into clearDeadPeers
* comment
* Merge branch 'clearDeadPeers' of https://github.com/prysmaticlabs/geth-sharding into clearDeadPeers
2020-06-26 12:24:55 +00:00
dv8silencer
812a663671 Add flag to allow reading bootstrap nodes from a file (#6351)
* parent c837dfb2f2
author dv8silencer <dv8silencer+github@gmail.com> 1592805180 -0500
committer dv8silencer <dv8silencer+github@gmail.com> 1592855989 -0500
Create a bootstrap-node-file flag which reads nodes from a YAML file and make the flag mutually exclusive to the bootstrap-node flag
* Merge branch 'master' into dv8s-iss6316
* Refactor so that boot node reading is in its own function.  Added test
* Added period

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Merge branch 'master' into dv8s-iss6316
* Edit Bazel to include go-yaml dep
* Help Bazel build successfully
* Merge branch 'master' into dv8s-iss6316
* bazel run //:gazella -- fix
* Handle error from YAML parser to address build checks
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Updated flags.go to refine the Usage for the BootStrapNodeFile flag

Co-authored-by: Nishant Das <nish1993@hotmail.com>
* Merge branch 'master' into dv8s-iss6316
* Utilize stdlib TempFile to avoid polluting
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* merge master into this branch
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Merge branch 'master' into dv8s-iss6316
* Changed bootstrap-node to StringSlice flag to allow multiple nodes to be passed.  Each value can be .enr file which will be YAML parsed to extract nodes
* Refactored to create separate readbootNodes function and added a test for it.
* More cleaning up
* Changed wording in the cli help for --bootstrap-node
* Merge branch 'master' into dv8s-iss6316
* Since we are taking YAML files, got rid of .enr check and instead we check for the string prefix of a enr record or not to determine if file.
* Merge with dv8silencer/tempissue6316
* Correct spacing

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Changed how we check for YAML file vs CLI-direct ENR
* Minor:  Changed to 1 string from concatenating 2
* Merge branch 'master' into dv8s-iss6316
2020-06-26 11:23:38 +00:00
terence tsao
461bc4694f QST40 QST42 QST44 - Move deletes to test scope only (#6410)
* Rm delete from interface
* Rm passthroughs
* Unexport
* Lint
* Merge branch 'master' into unexport-delete
* Merge refs/heads/master into unexport-delete
* Merge refs/heads/master into unexport-delete
* Merge refs/heads/master into unexport-delete
2020-06-26 04:29:13 +00:00
Preston Van Loon
806a465117 Remove unused p2p encoding method (#6411)
* Remove unused p2p encoding method
2020-06-26 04:02:09 +00:00
Raul Jordan
1b430e0c17 QSP-62 Corrupted Clock In Stream Deadlines (#6404)
* deadline warn
* add proper godoc information
* clarify
* Merge refs/heads/master into corrupted-clock
* fix broken build
* Merge refs/heads/master into corrupted-clock
* Merge refs/heads/master into corrupted-clock
2020-06-25 22:36:18 +00:00
Raul Jordan
6b27452947 QSP-39 AreEth1DataEqual Should Return True If Both Nil (#6372)
* resolve small core issue

* add tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-25 18:01:58 -04:00
terence tsao
ac69dbc2f8 Deprecates --disable-init-sync-batch-save-blocks flag (#6403)
* Deprecate flags in feature config

* Deprecate usages

* Update test

* Go fmt

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-25 15:55:43 -05:00
Raul Jordan
45e1c0bb8c QSP-54 Handle Default Datadir Empty String (#6394)
* default datadir
* Merge refs/heads/master into default-data-dir
* Merge refs/heads/master into default-data-dir
* Merge refs/heads/master into default-data-dir
* Merge refs/heads/master into default-data-dir
* Update node.go
* Merge refs/heads/master into default-data-dir
* Merge refs/heads/master into default-data-dir
* Merge refs/heads/master into default-data-dir
* Merge refs/heads/master into default-data-dir
* Merge refs/heads/master into default-data-dir
* Merge refs/heads/master into default-data-dir
2020-06-25 18:02:07 +00:00
Shay Zluf
9103ec98cb QSP-14 consistent file permissions (#6378)
* QSP-14 consistent file permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* default io file permissions
* Merge branch 'consistent_permissions' of github.com:prysmaticlabs/prysm into consistent_permissions
* fix comments
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* gaz
* Merge branch 'consistent_permissions' of github.com:prysmaticlabs/prysm into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Rename IoConfig.go to io_config.go
* Update shared/params/BUILD.bazel
* Merge refs/heads/master into consistent_permissions
* raul feedback
* Merge branch 'consistent_permissions' of github.com:prysmaticlabs/prysm into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* gaz
* Merge branch 'consistent_permissions' of github.com:prysmaticlabs/prysm into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
* Merge refs/heads/master into consistent_permissions
2020-06-25 16:12:59 +00:00
Victor Farazdagi
00f24f5729 Deprecates --disable-init-sync-wrr flag (#6400)
* deprecates wrr-related flag

* gofmt + gazelle

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-25 10:26:30 -05:00
Raul Jordan
90bfc9a395 QSP-49 Recalibrate Roughtime (#6393)
* roughtime recalibrate

* recalibrate roughtime

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-25 09:02:54 -05:00
Nishant Das
5fdf6310f7 add back handler (#6398)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-25 13:07:31 +03:00
Raul Jordan
662c5cd302 QSP-47 Remove Meaningless Relay Addr Check (#6388)
* add relay factory fix
* Merge refs/heads/master into qsp-47
* Merge refs/heads/master into qsp-47
* Merge refs/heads/master into qsp-47
* Merge refs/heads/master into qsp-47
* Merge refs/heads/master into qsp-47
* Merge refs/heads/master into qsp-47
* Merge refs/heads/master into qsp-47
* Merge refs/heads/master into qsp-47
* Merge refs/heads/master into qsp-47
2020-06-25 09:16:30 +00:00
Raul Jordan
26e27bf052 QSP-41 Clarify Block Filters Passthrough In DB (#6397)
* clarify filters
* Merge refs/heads/master into blocks-filter-criteria
* Merge refs/heads/master into blocks-filter-criteria
2020-06-25 08:31:07 +00:00
terence tsao
9a156bd73a Best practice follow up - remove outdated todos (#6392)
* Addressed 30.

* Remove outdated todos

* Go fmt

* Go fmt

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-24 23:14:11 -05:00
Preston Van Loon
412ea2dca1 Update CONTRIBUTING.md to include link to docs portal (#6396)
* Update CONTRIBUTING.md
* Merge branch 'master' into prestonvanloon-patch-1
2020-06-25 02:59:49 +00:00
Raul Jordan
0b178b446a QSP-64 Conditional for Rebuilding BlockRoots Trie in State Setters (#6390)
* rebuild trie for block roots
* Merge refs/heads/master into rebuild-trie-fix
* Merge refs/heads/master into rebuild-trie-fix
2020-06-25 02:03:18 +00:00
Preston Van Loon
fb8be4d555 Refactor BLS (#6395)
* refactor BLS to expose an interface rather than a single implementation
* Split up tests, gofmt, goimports, docs
* godoc for signature.Copy()
* more godocs
* revert gomod / deps changes
* rm newline
* revert proto changes
* rename bls12 to herumi for clarity
2020-06-25 00:47:51 +00:00
terence tsao
d0e2e0e979 Best practice feedback - part 1 (#6385)
* log error for metric
* reuse epoch e
* Better node comments
* Remove not needed breaks
* Use j over i
* Merge branch 'master' of github.com:prysmaticlabs/prysm into best-practice-pt1
* Descendent/Descendant
* Merge refs/heads/master into best-practice-pt1
* Update beacon-chain/forkchoice/protoarray/nodes.go
* Merge refs/heads/master into best-practice-pt1
* Merge refs/heads/master into best-practice-pt1
2020-06-24 21:09:47 +00:00
Raul Jordan
ac77a5c054 QSP-25 Only Enable Relay if Flag Provided (#6386)
* only add relay if flag is on
* Merge branch 'master' into qsp-25
* Merge refs/heads/master into qsp-25
* Merge refs/heads/master into qsp-25
2020-06-24 19:30:40 +00:00
terence tsao
a9c1d25a35 Best practice feedback - part 2 (#6389)
* Feedback 10. Rename to highest epoch
* Feedback 11. Rename to pidepoch
* Feedback 39. Swap length
* Typo
* Merge refs/heads/master into best-practice-pt2
2020-06-24 18:06:19 +00:00
Ivan Martinez
e27ed8174b Remove validator filename prefix from validator/client (#6387)
* Remove validator prefix from files
* Gaz
* Merge branch 'master' of github.com:prysmaticlabs/prysm into val-rename-files
2020-06-24 17:43:24 +00:00
Raul Jordan
bfce4c7f63 QSP-65 Clarify Why UnshuffleList is Used (#6381)
* clarify why unshuffle list
* Update beacon-chain/core/helpers/committee.go
* Merge branch 'master' into qsp-65
2020-06-24 16:57:09 +00:00
Nishant Das
045a983032 Add Altona Config (#6380) 2020-06-24 07:03:16 -07:00
Shay Zluf
b8e1bf0445 Fix proposer slashing context timeout test (#6379)
* Fix proposer slashing context timeout test
* goimports
* revert slashing change
* Merge branch 'master' into fix_proposer_slashing_test
2020-06-24 12:10:40 +00:00
Shay Zluf
edb08bd209 QPS-20 implement removeDisconnectedPeerStatus (#6370)
* QPS-20 implement removeDisconnectedPeerStatus
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* remove function
* Merge branch 'remove_disconnected_peer_status' of github.com:prysmaticlabs/prysm into remove_disconnected_peer_status
* Merge refs/heads/master into remove_disconnected_peer_status
* Merge branch 'remove_disconnected_peer_status' of github.com:prysmaticlabs/prysm into remove_disconnected_peer_status
2020-06-24 10:40:33 +00:00
Nishant Das
e45a06cbf1 Revert "QSP-42 Remove Double Unsubscribe in Initial Sync" (#6376)
* Revert "QSP-42 Remove Double Unsubscribe in Initial Sync (#6368)"

This reverts commit 637354f037.

* comment

* add go fmt
2020-06-24 17:01:48 +08:00
Ivan Martinez
e9a597b43c [QSP-6] Change usages of math/rand to crypto/rand (#6362)
* Change math/rand to crypto/rand
* Change length
* Merge branch 'master' of github.com:prysmaticlabs/prysm into change-to-crypto-rand
* Change assignments to true random
* Merge branch 'master' into change-to-crypto-rand
* Change randomness
* Merge branch 'change-to-crypto-rand' of github.com:prysmaticlabs/prysm into change-to-crypto-rand
* Remove comments
* Test
* Fix test
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
* Merge refs/heads/master into change-to-crypto-rand
2020-06-24 05:47:51 +00:00
terence tsao
a4cfd147ff Address spec adherence feedbacks (#6365)
* Addressed 1
* Address 2.
* Addressed 3. and 4.
* Addressed 6.
* Addressed 7
* Addressed 8
* Addressed 9.
* Addressed 10.
* Addressed 11.
* Addressed 12.
* Addressed 13.
* Delete old test
* Merge refs/heads/master into spec-feedbacks
* Change comment "pure" to "stateless"
* Fmt
* Typo
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
* Merge refs/heads/master into spec-feedbacks
2020-06-24 03:14:44 +00:00
Preston Van Loon
7662045cc6 Disable --enable-stream-duties for e2e tests (#6374)
* Disable --enable-stream-duties for e2e tests
* Merge branch 'master' into fix-e2e
* Merge branch 'master' into fix-e2e
* Merge branch 'master' into fix-e2e
2020-06-24 02:42:38 +00:00
Ivan Martinez
9fadb4f334 Address best practices in validator client (#6375)
* Best practices validator

* Add ctx

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-24 09:53:01 +08:00
Nishant Das
e9057185a5 Fix Peering Issues in Discovery (#6346)
* add current changes
* comment
* Merge branch 'master' into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* clean up
* add comment
* Merge refs/heads/master into fixPeeringIssues
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
* Merge refs/heads/master into fixPeeringIssues
2020-06-24 01:09:09 +00:00
Nishant Das
24d09f083f Release State Reference Copy (#6341)
* release flag
* add comment
* improve
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge branch 'master' into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into releaseStateRef
* remove old flags
* gaz
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
* Merge refs/heads/master into releaseStateRef
2020-06-24 00:24:59 +00:00
Raul Jordan
637354f037 QSP-42 Remove Double Unsubscribe in Initial Sync (#6368)
* rem double unsub
* Update beacon-chain/sync/initial-sync/service.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/master into qsp-unsub
* Merge refs/heads/master into qsp-unsub
* Merge refs/heads/master into qsp-unsub
* Merge refs/heads/master into qsp-unsub
* Merge refs/heads/master into qsp-unsub
2020-06-23 23:50:52 +00:00
terence tsao
c3adde3b32 QSP10, QSP11 - Add proper locking (#6350)
* Proper locking based on audit feedbacks
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Preston's feedback
* Merge branch 'qsp10-11' of github.com:prysmaticlabs/prysm into qsp10-11
* Unlock in invalid index branch
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge branch 'master' into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
* Merge refs/heads/master into qsp10-11
2020-06-23 23:08:08 +00:00
Raul Jordan
2bdb825c04 QSP-61 Clarify Why Process Pending Attestations May Exit Early (#6371)
* clarify with comment
* Merge refs/heads/master into qsp-61
* Merge refs/heads/master into qsp-61
* Merge refs/heads/master into qsp-61
2020-06-23 22:34:31 +00:00
Raul Jordan
7ba26aa433 Add Mutex to Hot State Cache (#6366)
* mutex to hot state cache
* Merge branch 'master' into add-hotstate-lock
* Merge refs/heads/master into add-hotstate-lock
* Merge refs/heads/master into add-hotstate-lock
2020-06-23 22:06:47 +00:00
terence tsao
374a84d577 Remove new state mgmt within db package (#6373)
* Remove new state mgmt within db package
* Merge refs/heads/master into rm-new-state-db
2020-06-23 21:36:21 +00:00
Raul Jordan
e1310adb4c QSP-Docs All Documentation Improvements from Quantstamp Audit Report (#6367)
* docs improvements so far
* all misc docs items
* finalized
* Merge branch 'master' into qsp-docs
* fix broken test
* Merge branch 'master' into qsp-docs
2020-06-23 21:11:20 +00:00
Preston Van Loon
f9038674d1 Refactor setupDB to return the state summary cache used by the database (#6369) 2020-06-23 13:40:55 -07:00
Victor Farazdagi
33b2636bf1 Enables new aggregation implementation (#6344)
* adds feature flag
* aggregations/attestation package
* better tests
* bazel visibility issues
* removes redundant code
* Merge branch 'master' into aggregation-attestations-package
* updates previous implementation
* Merge branch 'master' into aggregation-enable-new-aggregation
* resolve merge conflict
* resolve merge conflict (more)
* Merge branch 'master' into aggregation-enable-new-aggregation
* force max_cover aggregation on --dev
* Merge branch 'aggregation-enable-new-aggregation' of github.com:prysmaticlabs/prysm into aggregation-enable-new-aggregation
* Merge branch 'master' into aggregation-enable-new-aggregation
* Merge refs/heads/master into aggregation-enable-new-aggregation
* Merge refs/heads/master into aggregation-enable-new-aggregation
* Merge refs/heads/master into aggregation-enable-new-aggregation
* Merge refs/heads/master into aggregation-enable-new-aggregation
* Merge refs/heads/master into aggregation-enable-new-aggregation
2020-06-23 19:13:55 +00:00
Shay Zluf
96a110a193 External slashing protection not requiring signature (#6252)
* validation without signature
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* validation and update funcs
* Merge branch 'slashing_protection_no_sign' of github.com:prysmaticlabs/prysm into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge branch 'master' of github.com:prysmaticlabs/prysm into slashing_protection_no_sign
* Merge branch 'slashing_protection_no_sign' of github.com:prysmaticlabs/prysm into slashing_protection_no_sign
* change order
error handling
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* ivan feedback
* Merge branch 'slashing_protection_no_sign' of github.com:prysmaticlabs/prysm into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* add tests to blocks utils
* terence feedback
* reduce visibility
* Merge branch 'master' of github.com:prysmaticlabs/prysm into slashing_protection_no_sign

# Conflicts:
#	validator/client/polling/validator_attest.go
#	validator/client/polling/validator_propose.go
* fix metrics
* fix error
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* copy behaviour to streaming
* Merge branch 'slashing_protection_no_sign' of github.com:prysmaticlabs/prysm into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
* Merge refs/heads/master into slashing_protection_no_sign
2020-06-23 16:46:48 +00:00
terence tsao
c417b00675 Fix cold state replay to start at correct slot (#6361)
* Fix off by 1
* Regression tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-offset
* Go fmt
* Merge refs/heads/master into fix-offset
* Merge refs/heads/master into fix-offset
2020-06-23 16:04:42 +00:00
Ivan Martinez
81786159e9 Move permanent globally needed flags to shared/cmd and makes them accessible (#6312)
* Move permanent flags to shared/cmd and make them accessible
* Merge branch 'master' of github.com:prysmaticlabs/prysm into move-flags-to-cmd
* Add test
* Add comment
* Fix gaz
* Replace with new config
* Gaz
* replace
* gaz
* Merge branch 'master' into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Prestons comments
* Nishant comments
* Merge branch 'move-flags-to-cmd' of github.com:prysmaticlabs/prysm into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* Merge branch 'master' into move-flags-to-cmd
* Merge refs/heads/master into move-flags-to-cmd
* fmt
2020-06-23 15:41:20 +00:00
Anton
fe6cf9f33b SubscribeCommitteeSubnets fields length check (#6359)
* SubscribeCommitteeSubnets fields length check

A case where `len(req.Slots) != len(req.CommitteeIds)` but `len(req.CommitteeIds) == len(req.IsAggregator)`
should also throw an error. Without this fix only 2 length inequalities will throw the error.

Greetings from PwC Switzerland
* Added diff length SubscribeCommitteeSubnets test
* Merge branch 'master' into patch-1
2020-06-23 14:50:46 +00:00
Victor Farazdagi
078c157f56 Resolves issues from the best practices in beacon-chain/db (#6358)
* fixes 51
* fixes 52
* fixes 53
* fixes 54
* fixes 56
* Merge branch 'master' into db-best-practices
* fixes 62
* fixes 64
* fixes 65
* fixes 68
* fixes 69
2020-06-23 13:51:00 +00:00
Victor Farazdagi
22b3123ebe Resolves issues from the best practices in sync package (#6357)
* removes redundant locks
* fixes 37
* fixes 38
* reverts lock removal
* Merge branch 'master' into sync-best-practices-updates
* Merge refs/heads/master into sync-best-practices-updates
2020-06-23 12:00:29 +00:00
Victor Farazdagi
64b0f775d3 Fixes receiver name in db/kv (#6356)
* Fixes receinver name in db/kv
* Merge refs/heads/master into fix-receiver-name
* Merge refs/heads/master into fix-receiver-name
2020-06-23 10:15:01 +00:00
Victor Farazdagi
89ef3cfdc6 Fixes error message wording (#6355)
* fixes error message wording
* Merge refs/heads/master into fix-error-msg-wording
2020-06-23 09:44:39 +00:00
Nishant Das
36c82b26e4 Minor Improvements (#6353)
* minor improvements
* Update beacon-chain/sync/deadlines.go
* go fmt
2020-06-23 09:00:09 +00:00
Victor Farazdagi
5c90038007 Adds aggregation/attestations package (#6343)
* adds feature flag

* aggregations/attestation package

* better tests

* bazel visibility issues

* removes redundant code

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-22 23:00:38 -05:00
Raul Jordan
71a6c73e93 Remove All Instances of Kademlia from Prysm (#6323)
* fully remove kad
* Merge branch 'master' into rem-kad
* Update beacon-chain/p2p/service.go
* no workspace kad
* Merge branch 'rem-kad' of github.com:prysmaticlabs/prysm into rem-kad
* mod tidy
* Merge refs/heads/master into rem-kad
* Merge refs/heads/master into rem-kad
* Merge refs/heads/master into rem-kad
* add back bootnode query tool
* Merge branch 'rem-kad' of github.com:prysmaticlabs/prysm into rem-kad
* fix up multiaddr tests
* fix build
* fix up go build
* fix go build
* update dep
* Merge refs/heads/master into rem-kad
* Merge refs/heads/master into rem-kad
* Merge refs/heads/master into rem-kad
* Merge refs/heads/master into rem-kad
2020-06-23 02:53:11 +00:00
terence tsao
5c8da7a1c4 QSP58, QSP59 - Fix DB spans (#6352)
* Fix spans
* Merge refs/heads/master into qsp58-59
2020-06-23 02:22:22 +00:00
terence tsao
368af7e53f Clean up old block processing paths (#6311)
* Remove old block processing paths

* Go fmt

* Go fmt again

* Fix tests

* Using the wright receiver

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-06-22 17:19:33 -07:00
Victor Farazdagi
41c8ff4c1b Renames receiver in sync service (#6348)
* updates coinciding vars
* renames receiver in sync service
* Merge branch 'master' into sync-rename-receiver
2020-06-22 20:37:48 +00:00
terence tsao
c837dfb2f2 ActivationEligibilityEpoch nil case (#6347) 2020-06-22 14:41:21 -05:00
Nishant Das
3b2dc8346d Release State Field Trie (#6340)
* remove flag and references
* fix flag
* Merge refs/heads/master into releaseStateFieldTrie
* Merge refs/heads/master into releaseStateFieldTrie
2020-06-22 15:25:55 +00:00
Ivan Martinez
97315c8837 Add flat spans to slasher runtime (#6287)
* Add flat spans to runtime

* Fix tests

* Remove normal span cache from runtime

* Uncomment

* beyond lookback to db

* Remove heavy span

* better cache handling for disable lookback

* Fix lint

* Fix lint again

* Add cache back for now

* Update slasher/detection/attestations/spanner_test.go

* Fix imports

Co-authored-by: shayzluf <thezluf@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-06-22 09:55:52 -05:00
Victor Farazdagi
6f8349cdb4 Reclaims leakybucket resources in sync service (#6339)
* Reclaims leakybucket resources
* move calls to defer
* do not reuse queue, after stopping
2020-06-22 11:23:23 +00:00
Preston Van Loon
d4545233cd Fix race condition issues in beacon state (#6322)
* Fix race condition issues in beacon state
* Merge branch 'master' of github.com:prysmaticlabs/prysm into race-condition-fixes
* Checkout beacon-chain/state/stateutil/BUILD.bazel from master
* @nisdas PR feedback. defer unlock
2020-06-20 00:27:23 +00:00
rkapka
4f4846794a renamed variable (#6319) 2020-06-19 13:46:18 -07:00
Nishant Das
7e1a61f8eb Add Debug Endpoints For Peers (#6304)
* add debug endpoints

* gaz

* add more stuff

* add tests

* clean up

* Update beacon-chain/rpc/debug/server.go

* fmt

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-19 13:25:47 -05:00
Patrick
624209eba7 Fix Pagination Bug When Total Size % Page Size == 0 (#6266)
* Add failing test for pagination

* Fix failing test for pagination

* Fix other tests for pagination

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-06-19 09:39:12 -05:00
terence tsao
394f3ab53a Revert "Fetch deposit data only up to canonical Eth1 height when proposing (#6309)" (#6313)
This reverts commit fb26b0b65c.
2020-06-18 16:56:38 -07:00
rkapka
fb26b0b65c Fetch deposit data only up to canonical Eth1 height when proposing (#6309)
* get data up to canonical block height

* gofmt

* simplified calculation of canonical height
2020-06-18 17:31:26 -05:00
Victor Farazdagi
90542c21dc Implements max k-coverage greedy algorithm (#6305)
* implements max k-coverage greedy algorithm
* updates go-bitfield dependency
* gazelle
* update base aggregate
* re-arrange to shared
* clean references to atts in max cover
* max_cover: updates visibility
* fixes tests
* attestations related methods
* Merge branch 'master' into attaggregation-max-cover
* better op order
* fix comments
* removes debug stringer methods
* Merge refs/heads/master into attaggregation-max-cover
* log random seed
* Merge branch 'attaggregation-max-cover' of github.com:prysmaticlabs/prysm into attaggregation-max-cover
* Merge refs/heads/master into attaggregation-max-cover
* adds more comments
* Merge branch 'attaggregation-max-cover' of github.com:prysmaticlabs/prysm into attaggregation-max-cover
* fixes typo
2020-06-18 20:56:23 +00:00
Preston Van Loon
6926592065 Add a debug log statement when enabling dev flags (#6306)
* Add a debug log statement when enabling dev flags
* Merge refs/heads/master into add-dbg-log-for-dev-flags
2020-06-18 20:25:34 +00:00
Preston Van Loon
addc3897c4 Use STABLE_ prefix for git tag to force a relink of version (#6307)
* Use STABLE_ prefix for git tag to force a relink of version
* Add comment about STABLE_
2020-06-18 19:59:47 +00:00
Raul Jordan
7067c84c69 Stream Duties Client Implementation (#5867)
* include validator client stream

* Update validator/client/validator_attest.go

* gazelle

* rem extraneous logs

* fixing tests

* resolve most tests

* gaz

* add lock

* ivan feedback

* pass tests for update protect

* gaz

* duties gaz

* no need for canonical head slot

* fix ctx leak

* fmt

* add in feature flag

* add streaming subpackage

* add polling/streaming separation

* able to build

* fix duplicate package names

* fix polling

* imports

* confirm it works

* fixed up comment

* go lint comments

* gaz

* build

* Update validator/client/streaming/service_test.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* tidy

* fmt

* add stream duties to e2e

* add stream duties to e2e flags

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-06-18 13:30:05 -05:00
Jim McDonald
10af753f59 Unlock mutex on return (#6303)
Co-authored-by: Nishant Das <nishdas93@gmail.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-06-18 11:04:08 -05:00
Nishant Das
5201403750 update herumi (#6301)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-18 09:54:55 -05:00
Jim McDonald
86e9b0ae51 Ping handler timeout (#6302)
* Fix goroutine using cancelled context.

* Only close stream when finished

* Simplify function structure
2020-06-18 19:59:18 +08:00
Nishant Das
340ddf20cb Update Node RPC Endpoints (#6289)
* checkpoint progress
* some more stuff
* fix tests
* fix tests
* lint
* fix test and initialization
* gaz
* Merge branch 'master' into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
* Merge refs/heads/master into updateP2PRPC
2020-06-18 03:53:46 +00:00
Preston Van Loon
da5ab499da Add @prysmaticlabs/core-team as codeowner for deps.bzl (#6296)
* Add @prysmaticlabs/core-team as codeowner for deps.bzl
* Update CODEOWNERS
2020-06-18 03:38:02 +00:00
Paul Nelson
c1c3b75867 Move generic HashTreeRoot funcs to //shared (#6167)
* Functions that are to be moved to //shared/htrutils captured in separate file.

* Move files into new //shared/htutils package

hash_function.go renamed to hashers.go

* Refactor to reference moved methods in new package

- Added import for htrutils to state and stateutil packages
- Update references to imported funcs (append "htrutils.")
- Updated funcs in htrutils to be exported where necessary

* Add tests
2020-06-18 10:15:13 +08:00
terence tsao
640bba8a6c Avoid active validator count cache for genesis (#6292)
* Add helper to prevent zero hashes

* Test

* Don't use cache if it's genesis

* Regression test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-17 19:48:10 -05:00
terence tsao
6781bd643b Fix getting att pre state in sync (#6295) 2020-06-17 16:44:43 -07:00
terence tsao
802bdf5561 Fix GetValidatorPerformance before/after balances (#6293)
* Add helper to prevent zero hashes

* Test

* Fix precompute validators to have before/after balances

* Update tests to use correct values

* Even better test setups

* Gaz

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-17 13:46:42 -05:00
terence tsao
523fc621d9 First part of block chain service cleanup (#6286)
* Add helper to prevent zero hashes
* Test
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Remove ReceiveBlockNoPubsubForkchoice and rename ReceiveBlockInitialSync
* Apply feature flag to process_block.go
* Update mock and tests
* Update beacon-chain/blockchain/process_block.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/master into bc-pkg-cleanup
* Merge refs/heads/master into bc-pkg-cleanup
* Fix mock ReceiveBlockInitialSync. Thanks Victor!
* Merge branch 'bc-pkg-cleanup' of github.com:prysmaticlabs/prysm into bc-pkg-cleanup
* Merge refs/heads/master into bc-pkg-cleanup
* Merge refs/heads/master into bc-pkg-cleanup
2020-06-17 17:11:21 +00:00
Shay Zluf
472fbd3949 Less restrictive block stream for slashing detection (#6269)
* verify sig in stream

* state cache used

* fix import

* fix import

* fix tests

* add log for proposer slashing

* fix e2e

* use chain head to verify sig

* revert fix

* remove extra line

* add line

* revert extra log

* fix tests

* terence feedback

* fix

* fix test

* remove extra setup

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-17 12:38:07 -04:00
Ivan Martinez
cd439adfc7 Implement flat spans cache into DB (#6248)
* Implement flat spans cache DB

* Fix interface

* Fix db func

* Gaz

* Update slasher/detection/attestations/types/epoch_store_test.go

* Fix tests

* Fix

* Fix for comments

* Fix test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-06-17 10:26:08 -05:00
Raul Jordan
0bfa1ecd03 Clarify Insecure gRPC Connection Logs (#6276)
* clarify insecure conn
* fix up broken test
* Merge refs/heads/master into amend-grpc-instructions
* Merge refs/heads/master into amend-grpc-instructions
* Merge refs/heads/master into amend-grpc-instructions
* Merge refs/heads/master into amend-grpc-instructions
* Merge refs/heads/master into amend-grpc-instructions
* Merge refs/heads/master into amend-grpc-instructions
* Merge refs/heads/master into amend-grpc-instructions
2020-06-17 14:32:13 +00:00
terence tsao
af3122a9e8 Fork choice avoids redundant call to get_ancestor (#6282)
* Add helper to prevent zero hashes

* Test

* Add cacheJustifiedStateBalances

* Cache justifed balances

* Use cached justified balances

* Remove unncessary justification checks during initial syncing

* Test

* Proper locking

* Use getter

* Add CheckPointIsEqual helper

* Test CheckPointIsEqual helper

* Update finalizedImpliesNewJustified

* Better tests for finalizedImpliesNewJustified

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-17 08:50:10 -05:00
Preston Van Loon
4740f7ed57 pre-allocate memory for AggregateVerify (#6285)
* pre-allocate memory for AggregateVerify
2020-06-16 23:21:31 +00:00
Preston Van Loon
213be4cfbe Verify many block attestations at once (#6277) 2020-06-16 14:19:10 -07:00
Preston Van Loon
5fa3bbb991 Add --initial-sync-verify-all-signat as a dev flag. Issue #5176. (#6283) 2020-06-16 11:06:32 -07:00
terence tsao
fe2f8a1c04 Use justified balances for fork choice (#6272) 2020-06-16 08:10:34 -07:00
Nishant Das
ed883c9fff More Fixes For Powchain (#6278)
* fix issues

* add check

* Update beacon-chain/powchain/service.go

* Update beacon-chain/powchain/service.go

* Update beacon-chain/powchain/service.go

* Update beacon-chain/powchain/service.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-06-15 21:07:20 -05:00
terence tsao
4c143f4ed4 Fix underflow in resyncIfBehind (#6274) 2020-06-15 16:46:36 -07:00
Preston Van Loon
8097eea607 Fix underflow in SlotsSinceGenesis (#6275)
* Fix an underflow in genesis time calculation
* goimports
2020-06-15 21:56:11 +00:00
Ivan Martinez
4b4a7459d9 Fix windows DB path error and make errors more concise (#6270)
* Make DB errors more verbose, fix windows path error
* Merge branch 'master' into windows-err
* Merge refs/heads/master into windows-err
* Merge refs/heads/master into windows-err
2020-06-15 20:00:35 +00:00
Ivan Martinez
bf548d1670 Fix validator creation path (#6271)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-15 12:27:45 -07:00
terence tsao
e59ee2f203 Fix validator summary reporting (#6267)
* Add helper to prevent zero hashes
* Test
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Update validator summary
* Update existing tests to work with new indices
* Remove extra log
* Gazelle
* Merge branch 'master' into fix-validatory-summary
* Merge refs/heads/master into fix-validatory-summary
* Merge refs/heads/master into fix-validatory-summary
2020-06-15 17:25:58 +00:00
Raul Jordan
83d1aa8fa2 Default BeaconRPCProvider for Validator Should Match Beacon Node's Host (#6268)
* default bind to localhost for validator
* Merge branch 'master' into validator-localhost
2020-06-15 16:52:15 +00:00
Victor Farazdagi
9d42148b93 Go mod tidy (#6264)
* updates go.sum
* go mod tidy checker
* reverts go.sum
* updates apk command
* fixes path
* show git status
* more debug info
* more debug info
* minor test
* get rid of git
* multiple checks
* test reset
* change order of checkers
* mod verify
* broken sum
* Merge refs/heads/master into go-mod-tidy
* better info
* Merge branch 'go-mod-tidy' of github.com:prysmaticlabs/prysm into go-mod-tidy
* better info
* reset
* run go mod tidy to fix
2020-06-15 16:15:54 +00:00
Nishant Das
87084ec9f1 fix issues (#6265) 2020-06-15 10:43:45 -05:00
Victor Farazdagi
ebd45ba336 updates go.sum (#6262) 2020-06-15 06:37:07 -07:00
Nishant Das
9d8420b20c Fix Discovery Panic (#6261)
* fix dv5 panic
* add back
2020-06-15 04:22:29 +00:00
terence tsao
a9070ad725 ActiveValidatorCount to use cache (#6254)
* Add helper to prevent zero hashes

* Test

* Add ActiveIndicesCount getter for committee cache

* ActiveIndicesCount test

* ActiveValidatorCount to use cache

* Update cache on miss

* Update tests
2020-06-14 15:24:49 -07:00
terence tsao
f4e9e2f49c Minor clean up to 6249 (#6253)
* Add helper to prevent zero hashes

* Test

* Comments

* Comments
2020-06-14 10:43:25 -07:00
Nishant Das
1dfeb645b6 Filter Peers Properly With Connection Gater (#6251)
* add new filtering
* add new tests
* gaz
* shay's review
* Merge branch 'master' into fixFiltering
2020-06-14 14:47:58 +00:00
Nishant Das
933ab6808b mark peer as bad (#6250) 2020-06-14 07:10:18 -07:00
Nishant Das
f9d80e4a28 Fix Genesis Justified Checkpoints (#6249)
* handle zero hash
2020-06-14 09:02:56 +00:00
Ivan Martinez
f6ecf66d1a Fix pubkey used in validator metrics (#6246)
* Fix validator metrics pubkey
* Merge branch 'master' into val-metrics
2020-06-14 08:28:26 +00:00
Nishant Das
caf61bd824 Use Connection Gater to Manage Peer Connections (#6243)
* use gater
* Merge branch 'master' into connGater
* Update beacon-chain/p2p/testing/p2p.go
* fmt
* gaz
2020-06-14 07:35:05 +00:00
terence tsao
87ba5a5993 Fix ancestor to return most recent root in the case of skip slot (#6242)
* Revert "remove excess copies (#6142)"

This reverts commit c956905cf0.
* Update ancestor function to handle skip slot
* Test
* Revert "Revert "remove excess copies (#6142)""

This reverts commit f1222b5e77.
* Merge refs/heads/master into fix-ancestor
2020-06-14 06:58:36 +00:00
Nishant Das
0067e52b1e Revert "Remove Excess State Copies" (#6240)
* Revert "remove excess copies (#6142)"

This reverts commit c956905cf0.
2020-06-14 06:34:33 +00:00
Shay Zluf
4c66edf2c2 Add cache for flan spans (#6199)
* flat span cache

* Plug cache into kv

* Add comments

* Fix

* Add doc.go

* Gaz

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-13 22:51:54 -04:00
terence tsao
c29cccf78e Don't regen parent state for genesis state (#6237) 2020-06-13 11:04:04 -07:00
Raul Jordan
298955c92b Add a Log for Newly Connected gRPC Clients in the Beacon Node (#6233)
* interceptor disable logging via feature flag
* Merge branch 'master' into validator-connection-logs
2020-06-12 20:41:05 +00:00
Raul Jordan
de45a54991 Do Not Ignore Max Gateway Size gRPC (#6232)
* do not ignore max message size in gateway
* fix build
2020-06-12 20:02:20 +00:00
Raul Jordan
87ca73d605 Countdown Until Genesis (#6231)
* added in logic
* latest countdown
* fixed up formatting and add tests
* ready for review
* Merge branch 'master' into countdown-genesis
* no log if after genesis
* Merge branch 'countdown-genesis' of github.com:prysmaticlabs/prysm into countdown-genesis
* countdown
* smarter logging
* added buffer period for countdown
* Merge refs/heads/master into countdown-genesis
2020-06-12 18:47:18 +00:00
terence tsao
bc76c95d62 Skip proposer duty calculation for slot 0 (#6228)
* Skip proposer assignment for slot 0

* Test

* Clear cache before test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-12 11:20:50 -07:00
Preston Van Loon
c461c72777 Add dockerhub image endpoints (#6230)
* Add dockerhub image endpoints
2020-06-12 17:06:12 +00:00
Nishant Das
c725a9c8f2 Sort Duplicate Blocks In Response (#6222)
* sort out new blocks
* add unit test
* Merge refs/heads/master into sortDuplicates
* victor's review
* Merge branch 'sortDuplicates' of https://github.com/prysmaticlabs/geth-sharding into sortDuplicates
* Merge refs/heads/master into sortDuplicates
2020-06-12 13:50:07 +00:00
Nishant Das
412da8e7cc Follow Up to #6225 (#6226)
* don't wait
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into dontWait
* revert some changes
* bring back
2020-06-12 13:23:29 +00:00
Nishant Das
82f4d6a14a Do Not Wait Till Genesis (#6225)
* don't wait
2020-06-12 11:44:04 +00:00
Preston Van Loon
89762492c8 Reduce JSON-RPC queries (#6221)
* Delete unused client property
* Only update the logs every 5 minutes
* Merge branch 'master' into reduce-json-rpc-calls
* Merge refs/heads/master into reduce-json-rpc-calls
* Merge refs/heads/master into reduce-json-rpc-calls
* PR feedback from @nisdas
* gofmt
* Merge branch 'reduce-json-rpc-calls' of github.com:prysmaticlabs/prysm into reduce-json-rpc-calls
2020-06-12 04:05:40 +00:00
Nishant Das
1a6edbbaa2 Fix Proposer Bug in Prysm (#6213)
* advance slots instead of setting slots
* Merge branch 'master' into fixProposerBug
* comment
* Merge branch 'fixProposerBug' of https://github.com/prysmaticlabs/geth-sharding into fixProposerBug
* Refactor `packAttestations` to utilize same advanced state
* Merge branch 'master' into fixProposerBug
* Merge branch 'master' into fixProposerBug
* Merge branch 'master' into fixProposerBug
* Merge refs/heads/master into fixProposerBug
* Merge refs/heads/master into fixProposerBug
* Update beacon-chain/rpc/validator/proposer.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/master into fixProposerBug
2020-06-11 23:05:10 +00:00
SjonHortensius
409b167899 Provide some feedback to user when creating an account (#6212)
* Provide some feedback to user when creating an account

on my 1y old server the first step took 2 minutes, the second took 4
minutes. Provide at lease _some_ feedback we are doing something
intensive
* Merge branch 'master' into master
* Merge branch 'master' into master
* Merge branch 'master' into master
* Merge branch 'master' into master
2020-06-11 22:36:08 +00:00
Raul Jordan
abec538fda Prevent Whistleblower Index Bug (#6219)
* resolve proposer panic

* proposer is whistleblower

* import

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-11 15:08:26 -05:00
Shay Zluf
898cd8b42b No sig slasher rpc (#6174)
* detect slashable attestations and blocks without db update
* lint fixes
* fix mock
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* preston feedback
* Merge branch 'no_sig_slasher_rpc' of github.com:prysmaticlabs/prysm into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* nishant and ivan feedback
* Merge branch 'no_sig_slasher_rpc' of github.com:prysmaticlabs/prysm into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Merge refs/heads/master into no_sig_slasher_rpc
* Apply suggestions from code review
2020-06-11 18:50:12 +00:00
Ivan Martinez
ec6309a928 Cleanup flat spans implementation (#6150)
* Flat spanner improvements

* Fix tests, add more to ES type

* Move types to detection/types

* Fix

* Fix comments

* Fixes

* Use SlotTickerWithOffset for StreamIndexedAttestations (#5999)

* Change streamindexed to slot ticker with offset
* Make 2/3rds
* Add test
* Merge branch 'master' of github.com:prysmaticlabs/prysm into ticker-offset
* Add check for offset
* Merge branch 'master' of github.com:prysmaticlabs/prysm into ticker-offset
* Fix test
* Merge refs/heads/master into ticker-offset

* Fix long running E2E after v0.12 changes (#6008)

* Fix deposits in long run e2e

* Fix participation

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Small fixes for slasher  (#6021)

* Small fixes for slasher

* Remove useless log

* Fix test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Add voluntary exit processing to E2E (#6016)

* Add voluntary exit to E2E

* Fix long urnning e2e

* Fix for comments

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Change slashing pool to use spec code  (#6030)

* Change slashing pool to use more spec code

* Fix test

* Undo unneeded changes

* Make sure to catch regression

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Fix long-running E2E (#6047)

* Fixes for long running E2E
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-e2e
* Move metrics check up
* Merge refs/heads/master into fix-e2e

* E2E Improvements (#6091)

* Some fixes
* Merge branch 'master' into e2e-fixes
* Add another small delay
* Merge branch 'e2e-fixes' of github.com:prysmaticlabs/prysm into e2e-fixes
* Remove genesis test, make normal e2e run longer
* Gaz
* more fixes
* Merge branch 'master' into e2e-fixes
* Merge refs/heads/master into e2e-fixes
* Fix comment
* Merge refs/heads/master into e2e-fixes

* Begin changing tests

* Start work on tests

* Redo tests for EpochStore

* Add test for highest index

* Fixes

* Gaz

* Fix

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-11 14:17:44 -04:00
Raul Jordan
2fb485598b Resolve Nil Validator Panic (#6218)
* resolve proposer panic
* Merge refs/heads/master into panic-proposer-slashed
2020-06-11 17:38:03 +00:00
terence tsao
cf3260b948 Revert "Send blocks that fails validation to slasher" (#6217)
* Revert "Send blocks that fail p2p validation to slasher (#6164)"

This reverts commit f40a7575de.
* Merge branch 'master' into revert-6164-slasherP2P
2020-06-11 17:11:28 +00:00
terence tsao
83242466f4 Fix proposer calculation in sync (#6214) 2020-06-11 09:31:01 -07:00
Nishant Das
7f3dc5a2dd Adds a User Agent for Libp2p (#6211)
* Add the latest git tag as part of the version string.

Example:

version=Prysm/v1.0.0-alpha.10/28e61fa40c7d16774b3b1c18d8382c64537bfa84. Built at: 2020-06-11 04:29:18+00:00

* add user agent

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-11 10:34:34 -05:00
Ivan Martinez
260847e92f Fix long running E2E deposits testing (#6208)
* Fix long running e2e deposit processing
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-long-e2e
* Remove logs
* Uncomment
* typing
* Reorder
* Add const for node count
* Merge refs/heads/master into fix-long-e2e
* Add trace logging
* Merge branch 'fix-long-e2e' of github.com:prysmaticlabs/prysm into fix-long-e2e
2020-06-11 06:38:15 +00:00
Preston Van Loon
8815f6ced8 Add the latest git tag as part of the version string. (#6210)
Example:

version=Prysm/v1.0.0-alpha.10/28e61fa40c7d16774b3b1c18d8382c64537bfa84. Built at: 2020-06-11 04:29:18+00:00
2020-06-11 13:45:31 +08:00
Fabrice Cheng
28e61fa40c Verify External IP is reachable or log a warning if not (#6155)
* Only build with cgosymbolizer when explicitly desired. This fixes go builds for mac and others

* Try to dial external IP set and display a warning message is not reachable

* fix dialTimeout adding the port

* add connectivity check for UDP as well

* add connectivy verification for both UDP and TCP and move function in p2p/utils.go

* return if Resolving UDP fails

* move constant in utils

* add missing time dependencies

* leverage dial for both TCP/UDP (even thoguh UDP is not supported & add a unit tests for `verifyConnectivity`

* handle err from conn.Close()

* add utils_test go p2p gazelle

* Update beacon-chain/p2p/utils.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* Update beacon-chain/p2p/utils.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* Update beacon-chain/p2p/utils.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* do not defer closing the connection

* leverage util helper testutil.AssertLogsContain and testutil.AssertLogsDoNotContain

* remove old code

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
2020-06-10 18:41:11 -05:00
terence tsao
edeb359ded Use SSZ HTR as baseline (#6207)
* Use ssz htr as baseline to compare
* Merge branch 'master' into fix-test
* One more. Fix for TestBlockBodyRoot_NilIsSameAsEmpty
* Merge branch 'fix-test' of github.com:prysmaticlabs/prysm into fix-test
2020-06-10 17:51:06 +00:00
Shay Zluf
f40a7575de Send blocks that fail p2p validation to slasher (#6164)
* send blocks that fails validation to block feed for slasher. in order to enable slashing proposers

* add sig validation

* fix imports

* Update shared/featureconfig/config.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* Update shared/featureconfig/config.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* Update shared/featureconfig/flags.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* remove extra validation path for slasher

* ivan feedback

* notify all blocks that pass minimal validation to block stream

* notify all blocks that pass minimal validation to block stream

* add to e2e flags

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-10 13:24:05 -04:00
Nishant Das
a9e3ea3ccc Add Host Flags for All Servers running in Prysm (#6202)
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into removeHardLimit

# Conflicts:
add flags for all hosts
* lint
* Merge refs/heads/master into addFlagsForHosts
* Merge refs/heads/master into addFlagsForHosts
* Merge refs/heads/master into addFlagsForHosts
* use single flag
2020-06-10 16:04:32 +00:00
Jim McDonald
61855bc596 Add block number to deposit log (#6200)
* Add block number to deposit log
* Update beacon-chain/powchain/log_processing.go

Co-authored-by: Nishant Das <nish1993@hotmail.com>
* Merge branch 'master' into log-deposit-block
* gofmt
* Merge branch 'master' into log-deposit-block
2020-06-10 14:31:58 +00:00
Nishant Das
d66570c72b change gateway port (#6203) 2020-06-10 06:56:39 -07:00
Victor Farazdagi
1ffd13c4f5 Disallows empty string as validator password (#6201)
* allows empty string as validator password
* disallow empty pass on validator creation
* reset
2020-06-10 13:12:19 +00:00
Preston Van Loon
89e1b0f6bb Add --random flag for unencrypted keygen (#6194)
* Add --random flag for unencrypted keygen
* gofmt
2020-06-10 07:13:47 +00:00
Preston Van Loon
ae4a8b3aeb Update RBE toolchain and image to have libgmp-dev with bazel 3.2.0 (#6193)
* Update RBE toolchain and image to have libgmp-dev with bazel 3.2.0
* Merge branch 'master' into update-cross-compile
* some fixes for herumi cross compile
* gaz
2020-06-10 04:08:02 +00:00
Preston Van Loon
1f20cbb3f0 Update bootnode ENR for Onyx (#6192)
* Update bootnode ENR for Onyx
* Merge refs/heads/master into update-bootnode
2020-06-10 01:38:27 +00:00
Nishant Das
8188fc0f9e Use Updated Connection Manager (#6184)
* introduce updated connection manager
* Merge branch 'master' into removeHardLimit
* remove forked connection manager
* Merge branch 'removeHardLimit' of https://github.com/prysmaticlabs/geth-sharding into removeHardLimit
* Merge branch 'master' into removeHardLimit
* Merge branch 'master' into removeHardLimit
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into removeHardLimit
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into removeHardLimit

# Conflicts:
tidy up
* Merge branch 'removeHardLimit' of https://github.com/prysmaticlabs/geth-sharding into removeHardLimit
2020-06-10 00:22:45 +00:00
Nishant Das
d1a1043ef1 Update to v0.12 (#5614) 2020-06-09 15:40:48 -07:00
Preston Van Loon
47dacb88f7 Make a simple json-rpc call to ensure we are connected to a real ETH1 node (#6191)
* Make a simple json-rpc call to ensure we are connected to a real node
* Merge refs/heads/master into check-connection
2020-06-09 21:26:15 +00:00
Victor Farazdagi
50af507407 Improves operations/attestations/kv test coverage (#6181)
* fixes span names
* TestKV_SaveUnaggregatedAttestation tests added
* TestKV_SaveUnaggregatedAttestations test
* adds count tests
* TestKV_Unaggregated_CanDelete
* fixes naming
* Merge branch 'master' into att-pool-kv-cleanup
* better naming
* Merge branch 'att-pool-kv-cleanup' of github.com:prysmaticlabs/prysm into att-pool-kv-cleanup
* naming
* TestKV_Aggregated_SaveUnaggregatedAttestation added
* Merge branch 'master' into att-pool-kv-cleanup
* naming
* updates TestKV_Aggregated_HasAggregatedAttestation
* updates delete tests
* fix order
* Merge branch 'master' into att-pool-kv-cleanup
2020-06-09 21:00:36 +00:00
Victor Farazdagi
187e08d38d Inverts enable-init-sync-wrr flag (#6187)
* Inverts enable-init-sync-wrr flag
2020-06-09 19:16:59 +00:00
terence tsao
568d8c7825 Invert reduce attester state copies (#6185)
* Invert cfg.ReduceAttesterStateCopy flag

* Fix build
2020-06-09 11:47:23 -05:00
Nishant Das
c956905cf0 remove excess copies (#6142)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-09 10:11:11 -05:00
Victor Farazdagi
bea2b3420e Fixes span naming in rpc/validator (#6182)
* fixes span names
2020-06-09 12:28:16 +00:00
terence tsao
0387641662 Add debug endpoint for individual vote status (#6166)
* Add IndividualVotesRequest protos

* Inplement GetIndividualVotes

* Tests

* Build

* Move from debug server to beacon server

* Remove protos

* Remove gen code

* Typo and build

* Gazelle

* Better mock

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-08 21:37:56 -05:00
Victor Farazdagi
ba63186c92 Init-sync queue assert order and uniqueness of blocks emitted (#6146)
* removes duplicate code
* Merge branch 'master' into init-sync-queue-dedup-blocks
* Merge refs/heads/master into init-sync-queue-dedup-blocks
* Merge refs/heads/master into init-sync-queue-dedup-blocks
* Merge refs/heads/master into init-sync-queue-dedup-blocks
* Merge refs/heads/master into init-sync-queue-dedup-blocks
* Merge refs/heads/master into init-sync-queue-dedup-blocks
* Merge refs/heads/master into init-sync-queue-dedup-blocks
* Merge refs/heads/master into init-sync-queue-dedup-blocks
* Merge refs/heads/master into init-sync-queue-dedup-blocks
* Merge branch 'master' into init-sync-queue-dedup-blocks
* removes notification
* Merge branch 'init-sync-queue-dedup-blocks' of github.com:prysmaticlabs/prysm into init-sync-queue-dedup-blocks
* adds test
* updates service
* get rid of deepequal for err check
* Merge refs/heads/master into init-sync-queue-dedup-blocks
2020-06-08 14:52:43 +00:00
Ivan Martinez
cb2813fa05 Force manual validator account creation (#6165)
* Force manual validator account creation

* Fix

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-08 09:03:14 -05:00
Preston Van Loon
8ffe9858ec Rename white/blacklist to allow/deny list (#6173)
* Rename white/blacklist to allow/deny list
* Deprecate flag properly
2020-06-08 04:35:15 +00:00
Preston Van Loon
323a272a80 Move dependencies to the deps.bzl file and out of the WORKSPACE (#6168)
* Move dependencies to the deps.bzl file and out of the WORKSPACE
2020-06-07 21:48:30 +00:00
terence tsao
113a49b61e Verify historical slots per archived point (#6159)
* Add check for slots point
* Test
* Gaz
2020-06-06 21:47:10 +00:00
Nishant Das
0b70c3ea85 Clean Up Discovery Filtering of Peers (#6128)
* clean up

* fix test

* rename

* context

* preston's review

* remove dep

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-05 22:46:36 -05:00
Nishant Das
a1e3fc9500 Fix Gossip Clock Disparity (#6141)
* fix disparity
* Merge refs/heads/master into fixGossipDisparity
* Merge refs/heads/master into fixGossipDisparity
* Merge refs/heads/master into fixGossipDisparity
* Merge refs/heads/master into fixGossipDisparity
* Merge refs/heads/master into fixGossipDisparity
* Merge refs/heads/master into fixGossipDisparity
2020-06-06 01:54:44 +00:00
Nishant Das
c06d61c3d0 fix issue (#6152) 2020-06-06 09:16:46 +08:00
terence tsao
6af7664a56 Check attestation has pre state before retrieving it (#6149)
* Use state util to get block root

* Move prestate to below

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-05 18:23:35 -05:00
Preston Van Loon
6c0fbcc622 Only build with cgosymbolizer when explicitly requested (#6151)
* Only build with cgosymbolizer when explicitly desired. This fixes go builds for mac and others
2020-06-05 22:21:43 +00:00
Raul Jordan
302b0f8c80 Use FastSSZ Everywhere Applicable (#6135)
* use fast ssz anywhere applicable
* use fastssz clearly
* Merge branch 'master' into use-fastssz
* Apply suggestions from code review
* imports
* Update beacon-chain/p2p/fork.go
* Merge branch 'master' into use-fastssz
* update go-ssz
* update go-ssz
* Merge refs/heads/master into use-fastssz
* Merge refs/heads/master into use-fastssz
2020-06-05 13:48:40 +00:00
Ivan Martinez
e37c9d1334 Log commit hash on slasher startup (#6138)
* Add version log to slasher
* Add slasher version log on startup
* Remove duplicate log
* Merge refs/heads/master into slasher-commit
* Fix tet
* Merge branch 'slasher-commit' of github.com:prysmaticlabs/prysm into slasher-commit
* Undo
* Fix log in rpc
* Merge refs/heads/master into slasher-commit
* Merge refs/heads/master into slasher-commit
* Merge refs/heads/master into slasher-commit
* Merge refs/heads/master into slasher-commit
2020-06-05 12:04:12 +00:00
Victor Farazdagi
fd3cb0be55 Re-enables multi-failure test case in round robin (#6143)
* re-enables multi-failure test case in round robin
2020-06-05 11:26:10 +00:00
Ivan Martinez
92f23df368 Fix inaccurate validator balance metrics (#6134)
* Fix balance metrics
* Reorder
* Add comment
* Merge refs/heads/master into fix-balance-metrics
* Add underflow check
* Merge refs/heads/master into fix-balance-metrics
* Merge refs/heads/master into fix-balance-metrics
* Merge refs/heads/master into fix-balance-metrics
2020-06-05 03:31:20 +00:00
Ivan Martinez
a4f4ab2b1a Use stateutil AttestationDataRoot instead of go-ssz (#6136)
* Change usages of ssz.HashTreeRoot(att.Data) to stateutil
* Gaz
* Tests
* Imports
* Merge branch 'master' into use-stateutil-attdata
* Fix tests
* Merge branch 'use-stateutil-attdata' of github.com:prysmaticlabs/prysm into use-stateutil-attdata
* Merge refs/heads/master into use-stateutil-attdata
* Merge refs/heads/master into use-stateutil-attdata
2020-06-05 01:32:08 +00:00
Ivan Martinez
edbeb9022b Remove unused bazel test target (#6140)
* Remove benc htarget
2020-06-05 01:04:11 +00:00
terence tsao
d3494045a2 Fix aggregator with unaggregated attestation (#6137)
* Use state util to get block root
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Add UnaggregatedAttestationsBySlotIndex
* Tests
* New TestSubmitAggregateAndProof_UnaggregateOk test
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-aggregator-broadcast
2020-06-05 00:06:45 +00:00
Shay Zluf
1372391b77 Pretty pcli (#6099)
* new spanner db structure

* pretty print ssz structures in pcli

* nishant feedback

* remove from workspace

* dependency

* update names

* add to go.mod

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-04 16:08:24 -05:00
Jeevan
c3ff5ecb23 Notify users' with warning about using default ETH 1.0 RPC (#6126)
* added warning for default flag; http-web3provider
* Merge branch 'master' into warn-default-providers
* Update beacon-chain/node/node.go
* Merge branch 'master' into warn-default-providers
2020-06-04 19:40:29 +00:00
Ivan Martinez
1022d9dba8 Add AttestationDataRoot to stateutil (#6119)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-04 13:59:41 -05:00
Victor Farazdagi
53b0c0f7ab Adds gofmt checker action to GitHub workflow (#6132)
* adds gofmt checker action to GitHub workflow
* gofmt applied
2020-06-04 16:16:45 +00:00
Victor Farazdagi
84ae840b5d Re-enable previous fetching algorithm testing (#6125)
* re-enable previous fetching algorithm testing
2020-06-04 11:26:02 +00:00
Ivan Martinez
24d315c6d1 Add public keys to response for GetValidatorPerformance (#6115)
* Add public keys to response for GetValidatorPerformance
* Merge branch 'master' into add-pubkey-resp
* Merge branch 'master' into add-pubkey-resp
* Fixed all the broken tests (#6117)
* Merge branch 'add-pubkey-resp' of github.com:prysmaticlabs/prysm into add-pubkey-resp
* Fix skip
* Merge branch 'master' into add-pubkey-resp
* Fix ethapis
* Merge branch 'master' into add-pubkey-resp
2020-06-04 04:55:29 +00:00
rkapka
9c13e78dbd Simplified validator flags (#6108)
* simplified validator flags
* corrected typo
* Merge branch 'master' into simplify-validator-flags
* Merge branch 'master' into simplify-validator-flags
* Merge branch 'master' into simplify-validator-flags
* Merge branch 'master' into simplify-validator-flags
* Merge branch 'master' into simplify-validator-flags
2020-06-04 02:23:17 +00:00
terence tsao
a8c13dcaf8 Add NewBeaconBlock to testutil (#6118)
* Use state util to get block root

* Add NewBeaconBlock
2020-06-03 20:21:36 -05:00
Ivan Martinez
2eff8704a5 Add indice to certain validator logs (#6092)
* Add indice to activation and accounts list command

* Add to more logs

* Fix wrong !

* Fix err

* Fix tests
2020-06-03 19:12:18 -04:00
Victor Farazdagi
c94511223b Assert gfind is available on OSX, for protobufs updates (#6112)
* Assert gfind is available on OSX, for protobufs updates
* wording
* Merge branch 'master' into fix-protobuf-upd-scripts
2020-06-03 21:15:37 +00:00
Raul Jordan
b2b78c8a79 Remove Websockets for ETH1 From Prysm (#6055)
* mark websockets flag as deprecated, begin removing uses
* powchain package now builds
* Merge branch 'master' into no-websocket
* use seconds per eth1 block
* fix tests
* Merge branch 'master' into no-websocket
* rem websocket req
* Merge branch 'no-websocket' of github.com:prysmaticlabs/prysm into no-websocket
* Merge refs/heads/master into no-websocket
* Merge refs/heads/master into no-websocket
* fix broken test
* Merge refs/heads/master into no-websocket
* Merge refs/heads/master into no-websocket
* Merge refs/heads/master into no-websocket
* Merge refs/heads/master into no-websocket
* Merge refs/heads/master into no-websocket
* Merge refs/heads/master into no-websocket
2020-06-03 20:28:16 +00:00
terence tsao
c4afb8e2e7 Save unaggregated att in beacon_aggregate_and_proof subscriber (#6109)
* Use state util to get block root
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Also save unaggregated att
* Merge refs/heads/master into fix-save-agg
* Handle error
* Merge branch 'fix-save-agg' of github.com:prysmaticlabs/prysm into fix-save-agg
* Test
* Merge refs/heads/master into fix-save-agg
2020-06-03 19:49:43 +00:00
Preston Van Loon
d2337d0ec1 Disable some static analysis checks for coverage builds (#6105)
* Disable some static analysis checks for coverage builds
* Merge branch 'master' into fix-coverage-builds
* disable lostcancel for third_party code
* Merge branch 'fix-coverage-builds' of github.com:prysmaticlabs/prysm into fix-coverage-builds
* Merge refs/heads/master into fix-coverage-builds
* A few lostcancel fixes
* Merge branch 'fix-coverage-builds' of github.com:prysmaticlabs/prysm into fix-coverage-builds
* Merge refs/heads/master into fix-coverage-builds
2020-06-03 19:22:48 +00:00
Ivan Martinez
4e96cbeae7 E2E Improvements (#6091)
* Some fixes
* Merge branch 'master' into e2e-fixes
* Add another small delay
* Merge branch 'e2e-fixes' of github.com:prysmaticlabs/prysm into e2e-fixes
* Remove genesis test, make normal e2e run longer
* Gaz
* more fixes
* Merge branch 'master' into e2e-fixes
* Merge refs/heads/master into e2e-fixes
* Fix comment
* Merge refs/heads/master into e2e-fixes
2020-06-03 18:44:13 +00:00
Raul Jordan
80539d9028 Enable JSON-HTTP Gateway by Default on Port 3000 (#6090)
* default port 3000 http gateway
* Merge refs/heads/master into default-gateway
* Merge refs/heads/master into default-gateway
* fix broken node test
* disable grpc gateway
* Merge refs/heads/master into default-gateway
* Merge refs/heads/master into default-gateway
2020-06-03 18:11:43 +00:00
Raul Jordan
75aaa5e07b fix bad root (#6096) 2020-06-03 11:26:07 -05:00
Victor Farazdagi
7429221f3f go fmt (#6101) 2020-06-03 06:42:22 -07:00
Preston Van Loon
e79ba096d6 Rollback libp2p kad dht dependency update (#6084)
* go get github.com/libp2p/go-libp2p-kad-dht@v0.2.1 github.com/libp2p/go-libp2p-kbucket@v0.2.3
* revert API changes
* one more API fix
* Merge refs/heads/master into rollback-kad-dht
* Merge refs/heads/master into rollback-kad-dht
2020-06-02 23:01:42 +00:00
rkapka
ac138eae7b Split validator databases (#6048)
* initial working implementation with a basic test
* merge validator enhancements
* added test dependency to db's build file
* Merge branch 'master' into merge-validators-enhancements
* changed formatting of public key
* Merge branch 'master' into merge-validators-enhancements
* Merge branch 'master' into merge-validators-enhancements
* removed unused import
* Merge branch 'merge-validators-enhancements' into split-validator-databases

# Conflicts:
#	validator/db/BUILD.bazel
#	validator/db/manage.go
#	validator/db/manage_test.go
* tests and small fixes
* extracted common functionality
* Merge branch 'master' into split-validator-databases

# Conflicts:
#	validator/accounts/account_test.go
#	validator/db/manage.go
#	validator/db/manage_test.go
* added missing test dependency to build file
* added missing flags to main.go
* applied code review suggestions
* renamed flags to avoid duplication
* Merge branch 'master' into split-validator-databases
* Merge branch 'master' into split-validator-databases
* removed redundant parenthesis
* Merge branch 'master' into split-validator-databases
* Merge branch 'master' into split-validator-databases
* Merge branch 'master' into split-validator-databases
* Merge branch 'master' into split-validator-databases
* Merge branch 'master' into split-validator-databases
* extracted defer errors to package-level variables
* Merge branch 'master' into split-validator-databases
* comply with error naming convention
* removed incorrect import
* Merge branch 'master' into split-validator-databases
2020-06-02 22:04:16 +00:00
Nishant Das
469499873b Add Sync Pool For Snappy (#6085)
* add pool for snappy

* Update beacon-chain/p2p/encoder/ssz.go

* comment added

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-06-02 14:02:21 -05:00
Shay Zluf
fd19fd10a9 New spanner db structure (#6061)
* new spanner db structure

* lint fixes

* go mod fix

* fix iface

* remove unused

* remove extra line

* change from db

* exported field

* exported field

* revert to original

* fix

* ivan feedback

* ivan feedback

* ivan feedback

* revert mod changes

* fix db impl

* gaz

* import fix

* Try to fix tests

* ivan feedback

* new epoch store

* added comment

* fix error

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
2020-06-02 10:41:21 -04:00
terence tsao
d152b48815 use stateutil.BlockRoot instead of ssz for forkchoice (#6075)
* Use state util to get block root
* Merge refs/heads/master into use-stateutil1
2020-06-01 23:45:57 +00:00
Nishant Das
afbe494e55 Update Geth Fork (#5865)
* update workspace
* new updates
* new commit
* fixes
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into updateGeth
* test fixes
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fixCreateconfig

# Conflicts:
fix test
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into updateGeth
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fixCreateconfig

# Conflicts:
update commit
* use geth's dep
* Merge branch 'master' into updateGeth
* update workspace
* fix again
* Merge branch 'updateGeth' of https://github.com/prysmaticlabs/geth-sharding into updateGeth
* Merge branch 'master' into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* fix osx builds
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* add execption and disable nilness
* remove redundant deps
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into updateGeth
* clean up
* go mod
* tidy
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Add patch to resolve panic until https://github.com/bazelbuild/rules_go/pull/2450 can be addressed
* Merge branch 'updateGeth' of github.com:prysmaticlabs/prysm into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
* Merge refs/heads/master into updateGeth
2020-06-01 22:03:33 +00:00
Nishant Das
e715339aab Fix Status Messages During Genesis (#6046)
* fix status messages
* fix finalized checkpoint
* remove code
* Merge refs/heads/master into fixStatusMessages
* Update beacon-chain/blockchain/service.go
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* fix
* fix test
* fix again
* fix
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
* Merge refs/heads/master into fixStatusMessages
2020-06-01 20:26:42 +00:00
Victor Farazdagi
4ed0e432e3 Fixes subsequence matching in deleteValueForIndices (#6071)
* fixes subsequence matching in deleteValueForIndices
* Merge branch 'master' into fix-delete-value-for-indices
* Merge refs/heads/master into fix-delete-value-for-indices
2020-06-01 19:00:47 +00:00
terence tsao
db9e02d7d1 Cache genesis block root (#6069)
* Don't forget to set genesis blockroot
* Typo
* Merge branch 'master' into set-genesis-blk-root
2020-06-01 17:39:09 +00:00
Raul Jordan
31ef6befde Add More Tests to CommitteeAssignments (#6028)
* add test
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* pass comm tests
* Merge branch 'comm-tests' of github.com:prysmaticlabs/prysm into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
* Merge refs/heads/master into comm-tests
2020-06-01 14:50:48 +00:00
Raul Jordan
c23ac8547f Ensure Consistent ListValidators RPC Results (#6054)
* run process slots on list vals call
* fix behavior
* Merge branch 'master' into bad-list-vals
* Merge refs/heads/master into bad-list-vals
* Merge refs/heads/master into bad-list-vals
* Merge refs/heads/master into bad-list-vals
* Merge refs/heads/master into bad-list-vals
* Merge refs/heads/master into bad-list-vals
* Merge refs/heads/master into bad-list-vals
2020-06-01 14:16:40 +00:00
Victor Farazdagi
261a343ea5 Fixes intersection functions (uint64, int64, []byte) (#6067) 2020-06-01 06:35:29 -07:00
Nishant Das
ceaceeb33c Reset Streams Properly (#6066)
* reset streams

* fix build
2020-06-01 16:14:47 +08:00
terence tsao
6598c38625 Forkchoice start using proper root (#6062)
* Skip update head if justiifed root is zero hashes

* Start with genesis root instead

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-06-01 11:32:34 +08:00
terence tsao
6e514b96fd Remove unused code (#6065)
* Ran code cleanup from goland

* Typo

* Remove unused code

* Gazelle

* Delete comments
2020-05-31 15:47:15 -07:00
terence tsao
6e3b78b99e Ran code cleanup from goland (#6064)
* Ran code cleanup from goland

* Typo
2020-05-31 15:08:36 -05:00
Preston Van Loon
49a0d3caf0 Refactor dependencies, make Prysm "go gettable" (#6053)
* Fix a few deps to work with go.mod, check in generated files

* Update Gossipsub to 1.1 (#5998)

* update libs

* add new validators

* add new deps

* new set of deps

* tls

* further fix gossip update

* get everything to build

* clean up

* gaz

* fix build

* fix all tests

* add deps to images

* imports

Co-authored-by: rauljordan <raul@prysmaticlabs.com>

* Beacon chain builds with go build

* fix bazel

* fix dep

* lint

* Add github action for testing go

* on PR for any branch

* fix libp2p test failure

* Fix TestProcessBlock_PassesProcessingConditions by updating the proposer index in test

* Revert "Fix TestProcessBlock_PassesProcessingConditions by updating the proposer index in test"

This reverts commit 43676894ab.

* Compute and set proposer index instead of hard code

* Add back go mod/sum, fix deps

* go build ./...

* Temporarily skip two tests

* Fix kafka confluent patch

* Fix kafka confluent patch

* fix kafka build

* fix kafka

* Add info in DEPENDENCIES. Added a stub link for Why Bazel? until https://github.com/prysmaticlabs/documentation/issues/138

* Update fuzz ssz files as well

* Update fuzz ssz files as well

* getting closer

* rollback rules_go and gazelle

* fix gogo protobuf

* install librdkafka-dev as part of github actions

* Update kafka to a recent version where librkafkfa is not required for go modules

* clarify comment

* fix kafka build

* disable go tests

* comment

* Fix geth dependencies for end to end

* rename word

* lint

* fix docker

Co-authored-by: Nishant Das <nishdas93@gmail.com>
Co-authored-by: rauljordan <raul@prysmaticlabs.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-05-31 14:44:34 +08:00
Ivan Martinez
d35531cb17 Add index to activationStatus and MultipleValidatorStatus response (#6026)
* Cleanup val status

* More cleanup

* Fix tests

* Fix tests again

* Change to nonExistentIndice

* Fix test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-29 13:17:27 -05:00
Ivan Martinez
213f8ef088 Fix long-running E2E (#6047)
* Fixes for long running E2E
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-e2e
* Move metrics check up
* Merge refs/heads/master into fix-e2e
2020-05-29 16:52:38 +00:00
rkapka
d1e2901b95 Merge validators enhancements (#6027)
* merge validator enhancements
* added test dependency to db's build file
* Merge branch 'master' into merge-validators-enhancements
* changed formatting of public key
* Merge branch 'master' into merge-validators-enhancements
* Merge branch 'master' into merge-validators-enhancements
* removed unused import
2020-05-29 15:57:10 +00:00
Victor Farazdagi
0243bdcf37 Fixes overflow issue in sync/pending_blocks_queue (#6039)
* fixes overflow issue
* Merge refs/heads/master into fix-overflow
* Merge refs/heads/master into fix-overflow
2020-05-29 13:50:41 +00:00
Victor Farazdagi
a0bf8cba52 Removes redundant type conversions (#6041)
* removes redundant type conversions
* remove redundant type in struct decl
* removes redundant parens
* Merge refs/heads/master into redundant-type-conversions
2020-05-29 12:42:39 +00:00
Victor Farazdagi
0eaf0cf27b Properly handles possible nil values (#6042)
* handles possible nil values
2020-05-29 12:09:04 +00:00
terence tsao
ac862d1e7e Increase hot state cache size to 32 (#6033)
* Increase hot state cache size to 16
* Merge refs/heads/master into hot-state-cache-size
2020-05-29 05:01:40 +00:00
Ivan Martinez
cde127354c Change slashing pool to use spec code (#6030)
* Change slashing pool to use more spec code

* Fix test

* Undo unneeded changes

* Make sure to catch regression

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-29 00:26:09 -04:00
Ivan Martinez
0b64db5e21 Add voluntary exit processing to E2E (#6016)
* Add voluntary exit to E2E

* Fix long urnning e2e

* Fix for comments

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-28 22:51:00 -04:00
Raul Jordan
88aaee36bf Fix Weird Pre-Genesis Timestamp (#6031)
* ensure test passes

* Apply suggestions from code review

* comment

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
2020-05-28 21:57:03 -04:00
terence tsao
3fe47c0043 Reduce attester state copies (#6025)
* Test

* Fix

* Removed extra line

* Feature flag

* Gaz
2020-05-28 13:33:08 -04:00
Ivan Martinez
7dd187c2ae Small fixes for slasher (#6021)
* Small fixes for slasher

* Remove useless log

* Fix test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-28 10:24:54 -04:00
terence tsao
e3180cf977 Invert state field trie (#6013)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-28 08:24:26 -05:00
Victor Farazdagi
9e8eafda6a Fixes problem in YAML front-matter of the new flag tracking issue template (#6023)
* fixes probleim in YAML front-matter
* Merge refs/heads/master into fix-feature-tracking-issue-template
2020-05-28 10:45:18 +00:00
Raul Jordan
9a2c684628 Recommend Users Blocked By Antivirus a Way to Curl Prysm.sh (#6019)
* recommend no revoke
* Merge refs/heads/master into antivirus
2020-05-28 10:00:19 +00:00
Nishant Das
979c0074c7 Register RPC And Pubsub Handlers After Genesis is Determined (#6020)
* fix
* fix test
2020-05-28 05:39:40 +00:00
Preston Van Loon
a139b75dc5 Add documentation and issue template for feature flags (#6018)
* Add details around feature flag usage and recommend filing tracking issues for feature flags.

* 🦄

* 🦄

* labels

* more comments
2020-05-27 20:37:37 -05:00
terence tsao
4c2ed410b0 Invert state ref copy flag (#6015)
* Revert "Release state-ref-copy flag (#6012)"

This reverts commit ebf7122d6f.

* Invert state ref copy flag
2020-05-27 14:30:54 -05:00
terence tsao
ebf7122d6f Release state-ref-copy flag (#6012)
* Release state ref copy flag
* Merge refs/heads/master into invert-flag1
2020-05-27 18:08:12 +00:00
terence tsao
b7c856af6f Add skip to log (#6014) 2020-05-27 12:35:54 -05:00
Nishant Das
7be8942079 Fix Fork Data in Local Node (#5997) 2020-05-27 08:07:40 -07:00
Ivan Martinez
29e4594783 Fix long running E2E after v0.12 changes (#6008)
* Fix deposits in long run e2e

* Fix participation

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-27 08:28:01 -05:00
Victor Farazdagi
f4778048ac Init sync arbitrary batch length + full bandwidth utilization (#5978)
* allow to jump over 50K skipped slots
* more tests
* removes debug logs
* minor fixes
* re-arrage pid updates
* optimizes queue and fsm
* Merge branch 'master' into init-sync-arbitrary-batch-len
* fixes benchmark test
* Merge branch 'master' into init-sync-arbitrary-batch-len
* queue cleanup
* updates polling interval
* fsm test: allMachinesInState
* fsm test: highestStartBlock
* rest of fsm tests
* Merge branch 'master' into init-sync-arbitrary-batch-len
* Merge refs/heads/master into init-sync-arbitrary-batch-len
* Merge refs/heads/master into init-sync-arbitrary-batch-len
* Merge refs/heads/master into init-sync-arbitrary-batch-len
* Merge refs/heads/master into init-sync-arbitrary-batch-len
* Merge refs/heads/master into init-sync-arbitrary-batch-len
* parse machines in order
* Merge branch 'init-sync-arbitrary-batch-len' of github.com:prysmaticlabs/prysm into init-sync-arbitrary-batch-len
2020-05-27 09:13:41 +00:00
terence tsao
0c3586a8ea Add debug proto array fork choice endpoint (#6003)
* Add proto array fork choice object to RPC
* Add pb
* Add pb
* Expose proto array store object
* Test
* Merge branch 'forkchoice-endpoint' of github.com:prysmaticlabs/prysm into forkchoice-endpoint
* s/Nodes/nodes
* Remove proto from gitignore
* More implementations of GetProtoArrayForkChoice
* Comments
* Use hex
* Gazelle
* GetForkChoice Test
* Remove pb.go
* Merge branch 'master' into forkchoice-endpoint
* Typo, thanks Raul!
* Merge branch 'forkchoice-endpoint' of github.com:prysmaticlabs/prysm into forkchoice-endpoint
2020-05-26 23:24:38 +00:00
Ivan Martinez
5afee4ba3a Use SlotTickerWithOffset for StreamIndexedAttestations (#5999)
* Change streamindexed to slot ticker with offset
* Make 2/3rds
* Add test
* Merge branch 'master' of github.com:prysmaticlabs/prysm into ticker-offset
* Add check for offset
* Merge branch 'master' of github.com:prysmaticlabs/prysm into ticker-offset
* Fix test
* Merge refs/heads/master into ticker-offset
2020-05-26 19:34:09 +00:00
Ivan Martinez
0f7cf212a2 Prepare E2E for v0.12 (#5991)
* Prepare e2e for v0.12

* Fix e2e

* Comments

* Attempt 100% participation

* Fixes

* Fix

* Update readme

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-26 14:04:42 -05:00
Ivan Martinez
ecea979b60 Change StreamIndexedAttestations to use target root for state regen (#5971) 2020-05-26 09:21:17 -07:00
Raul Jordan
ad1d8074d0 Improve Deposit Data Account Creation Prompt (#5985)
* improve validator accounts create text
* Merge refs/heads/master into improve-deposit-data-promt
* Merge refs/heads/master into improve-deposit-data-promt
* Merge refs/heads/master into improve-deposit-data-promt
* Merge refs/heads/master into improve-deposit-data-promt
2020-05-26 13:24:46 +00:00
Victor Farazdagi
c70c52b40a Runs go fmt and updates validator files (#5995)
* updates validator files
2020-05-26 11:13:12 +00:00
Martin Linkhorst
b724b20828 Add missing TLS-related flags to Beacon Chain and Slasher (#5984)
* beacon-chain: add missing slasher flags
* slasher: add missing tls-cert flag
* Merge branch 'master' into tls
* Merge branch 'master' into tls
2020-05-26 02:08:15 +00:00
rkapka
b3f005fe94 Fixed deferring of closing dbs (#5982)
* fixed deferring of closing dbs
* removed unnecessary slice pointer
* Merge branch 'master' into merge-defer-fix
* Merge branch 'master' into merge-defer-fix
2020-05-26 00:38:41 +00:00
terence tsao
3b65cb6d0b Consistent BLS function inputs (#5969)
* Make function input consistent

* Change back

* Typo

* Fixed test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-25 16:08:12 -05:00
Raul Jordan
497307decd Remove Warning on Using Default Mainnet Config (#5983)
* removed mainnet warn
2020-05-25 19:43:10 +00:00
Victor Farazdagi
f81c8c6825 Allow to jump over 50K+ skipped slots in init-sync (#5975)
* allow to jump over 50K skipped slots
* more tests
* removes debug logs
* minor fixes
* re-arrage pid updates
* Merge refs/heads/master into init-sync-50K-skipped-slots
2020-05-25 16:43:59 +00:00
rkapka
277fa3300a Merge validator databases (#5968)
* merge functionality

* merge testing

* log info when merge completed successfully

* extracted private methods

* fixed linter errors

* fixed compilation errors

* build files clean-up

* fixed failing test

* corrected command description

* close sources inside defer

* corrected documentation of NewKVStore
2020-05-25 11:20:35 -05:00
Ivan Martinez
b810243f41 Reverse historical detection flag for slasher (#5958)
* Reverse historical detection flag
* Merge branch 'master' of github.com:prysmaticlabs/prysm into reverse-historical-flag
* Merge branch 'master' of github.com:prysmaticlabs/prysm into reverse-historical-flag
* Fix build
* Merge refs/heads/master into reverse-historical-flag
* Fix test
* Merge branch 'reverse-historical-flag' of github.com:prysmaticlabs/prysm into reverse-historical-flag
* Merge refs/heads/master into reverse-historical-flag
2020-05-23 06:40:15 +00:00
Preston Van Loon
5a3114cdc9 Update BLS to allow for spec v0.12 requirements (#5914)
* update bls

* Update BLS, has a minor issue with blsVerifyAggregatedHashWithDomainCast. See https://github.com/herumi/bls-eth-go-binary/issues/17

* update

* fix build
2020-05-23 10:50:02 +08:00
Ivan Martinez
f9d847991c Add RemoveOldestFromCache and save span cache on exit (#5953)
* Add RemoveOldestFromCache
* Add log
* comment
* gaz
* Merge branch 'master' into prune-spancache-historical
* Merge refs/heads/master into prune-spancache-historical
* Merge refs/heads/master into prune-spancache-historical
* Fix span defer
* Merge branch 'prune-spancache-historical' of github.com:prysmaticlabs/prysm into prune-spancache-historical
* Merge refs/heads/master into prune-spancache-historical
* Update slasher/db/kv/kv.go
2020-05-22 19:44:48 +00:00
Ivan Martinez
6aabea2d80 Reverse broadcast-slashing flag to disable-broadcast-slashings (#5952)
* Reverse broadcast-slashings to disable-broadcast-slashings
* Fix tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into toggle-broadcast-flag
* Merge refs/heads/master into toggle-broadcast-flag
* Fix for comments
* Merge branch 'toggle-broadcast-flag' of github.com:prysmaticlabs/prysm into toggle-broadcast-flag
* Merge refs/heads/master into toggle-broadcast-flag
2020-05-22 17:19:45 +00:00
Ivan Martinez
230659467d Only log attester slashing found for valid slashings (#5954)
* Improve logging for slasher

* Add case for sig verify

* Log out indices for failed slashings

* gaz

* Fix test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-22 10:19:10 -05:00
Victor Farazdagi
c875dd458b Handles issue with empty dirs on validator accounts create (#5940)
* handles issue with empty dirs on validator accounts create
* better comments
* Merge refs/heads/master into fix-validator-accounts-create
* Merge refs/heads/master into fix-validator-accounts-create
* Terence's review
2020-05-22 11:00:41 +00:00
Nishant Das
6a9112bfae remove byte mempool (#5951) 2020-05-21 20:39:06 -07:00
terence tsao
8eb7c7a0bc Recover skipped archived point (#5950) 2020-05-21 18:15:16 -07:00
Ivan Martinez
4fb3307de3 Add Slasher double block detection to E2E (#5936)
* WIP double block slashings e2e
* Add double block detection to E2E
* Remove unused function
* Respond to feedback
* Remove unneeded util
* Merge branch 'master' of github.com:prysmaticlabs/prysm into e2e-double-block
* Add comments for clarity on conns
2020-05-21 06:02:40 +00:00
Raul Jordan
881ad77c52 Add Debug Block Endpoint + Return SSZ-Encoded (#5926)
* add block endpoint

* handle err

* check for nil block

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-20 20:36:05 -05:00
terence tsao
52988a0805 Return err instead of 0 for unavailable participation (#5934)
* Return err for unavailable participation

* Update     test
2020-05-20 18:47:40 -04:00
Ivan Martinez
5267fe607c Fix slasher pool to not ignore valid slashings (#5927)
* Improve slashing pool handling to not reject valid slashings
* Undo testing stuff
* Merge refs/heads/master into fix-slasher-pool
* Add regression test for pool changes
* Merge branch 'fix-slasher-pool' of github.com:prysmaticlabs/prysm into fix-slasher-pool
* Merge refs/heads/master into fix-slasher-pool
* Merge refs/heads/master into fix-slasher-pool
* Merge refs/heads/master into fix-slasher-pool
* Merge refs/heads/master into fix-slasher-pool
* Merge refs/heads/master into fix-slasher-pool
2020-05-20 20:27:23 +00:00
Ivan Martinez
9fc6be8b74 Change ListIndexedAttestations to be more slasher friendly (#5930)
* Improve slasher beacon comms
* Fixes
* Add case for normal errors
* remove baz
* Merge branch 'master' into improve-slasher-beacon
* Merge refs/heads/master into improve-slasher-beacon
* Merge refs/heads/master into improve-slasher-beacon
* Feedback
* Merge branch 'improve-slasher-beacon' of github.com:prysmaticlabs/prysm into improve-slasher-beacon
* Merge refs/heads/master into improve-slasher-beacon
2020-05-20 19:52:18 +00:00
terence tsao
5f72d28057 Blockchain service provides IsCanonical getter (#5932)
* Export `NonExistentNode` and `Root`
* Add mapping `recentCanonicalBlocks`
* Add `updateRecentCanonicalBlocks`
* Use `updateRecentCanonicalBlocks`
* New tests
* s/Root/root
* Lint
* Merge branch 'master' into is-canonical
* Merge refs/heads/master into is-canonical
2020-05-20 19:16:56 +00:00
Preston Van Loon
020c481a46 Enable domain data cache by default (#5931)
* Enable domain data cache by default
* Merge refs/heads/master into enable-domain-data-cache-by-default
2020-05-20 18:46:03 +00:00
Nishant Das
e3d07489dc Fix Flags in Create Subcommand (#5928)
* fix flag parsing
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into fixCreateconfig
* Merge refs/heads/master into fixCreateconfig
2020-05-20 18:19:30 +00:00
Nishant Das
49edcb099b Log Active Validator Count (#5923)
* add more verbose deposit count
* Merge branch 'master' into addBetterCount
* Merge refs/heads/master into addBetterCount
* Update beacon-chain/powchain/log_processing.go

Co-authored-by: Shay Zluf <thezluf@gmail.com>
2020-05-20 16:24:51 +00:00
Shay Zluf
17169e5a2d External slashing protection (#5895)
* slasher grpc client

* do not export

* slasher on a different package

* fix featureconfig

* change to rough time

* revert roughtime

* remove extra comma

* revert order change

* goimports

* fix comments and tests

* fix package name

* revert reorder

* comment for start

* service

* fix visibility

* external slasher validator protection implementation

* gaz

* fix comment

* add comments

* nishant feedback

* raul feedback

* preston feedback

* fix flags

* fix imports

* fix imports

* port 4002

* added tests

* fix log

* fix imports

* fix imports name

* raul feedback

* gaz

* terence comment

* change name

* runtime fixes

* add flag check

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-20 10:23:22 -05:00
Nishant Das
2de4f86277 Change To Debug Logs (#5917)
* debug
2020-05-20 04:57:24 +00:00
Raul Jordan
ea02edba29 Ensure We Use Request.Epoch in the Validator Duties Server Implementation (#5913)
* resolve bad epoch in duties
2020-05-19 21:26:14 +00:00
Victor Farazdagi
8241b7e20d Re-arranges fetcher locks -> per peer level (#5906)
* fetcher locks -> per peer level
* typo
* removes redundant setting to nil
* Merge refs/heads/master into init-sync-rearrange-locks
2020-05-19 17:48:32 +00:00
Ivan Martinez
aa6190235a Fix prysm.bat internet warning (#5908)
* Fix bat
* Remove %
* Merge branch 'master' into fix-bat
2020-05-19 17:24:47 +00:00
Preston Van Loon
5e6a5902ae Invert --enable-account-metrics to remove user confusion. See #5883 (#5904) 2020-05-19 08:44:54 -05:00
Michael Huang
62b617fa9a Command to fetch validator statuses + MultipleValidatorStatus (#5784)
* Add method to fetch account statuses
* Add status command
* gofmt
* Add comment about sorting
* Close conneciton when finished
* Fix error
* Refactor FetchAccountStatuses
* Add status_test.go
* Move sorting out of FetchAccountStatuses
* Remove unnecessary casting
* Expect ValidatorStatus to be called
* Wrap long comment
* Comment out sorting
* Add all necessary dial options
* Close connection before evaluating error from fetch
* Small changes
* Fix lint issues
* Merge branch 'master' into validator-client-account-statuses
* Update dependencies for docker images
* Rename multipleValidatorStatus to activationStatus
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Update commit hash for ethereumapis
* Implement MultipleValidatorStatus
* Tests for MultipleValidatorStatus
* Fix bugs
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Add export comment for MultipleValidatorStatus
* Run `go fmt` in prysm (#5815)

* go fmt
* Add fix for nil state in InitializeFromProto (#5817)

* Add nil check and tests
* Add unsafe test
* Update tools/genesis-state-gen/main.go
* Undo genesis state gen changes
* Merge branch 'proto-fuzz-fix' of github.com:prysmaticlabs/prysm into proto-fuzz-fix
* gaz
* Fix
* Add export comment for MultipleValidatorStatus
* Clean up comments
* Update mock files for beacon_node_validator_service
* Merge branch 'validator-client-account-statuses' of https://github.com/michaelhly/prysm into validator-client-account-statuses
* Run gazelle
* Fix mock issues
* Fetch statuses in batches
* Simplify public key generation for status_test
* Sort validator statuses by status type
* Format validator statuses and print to console
* Fix lint issues
* Delimit with commas
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Rename otheropts to extraopts
* Merge branch 'master' into validator-client-account-statuses
* Merge branch 'validator-client-account-statuses' of https://github.com/michaelhly/prysm into validator-client-account-statuses
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Clean up MultipleValidatorStatus tests
* Add sync checker to MultipleValidatorStatus
* Update formatting
* Prepend 0x to validator keys
* Check number of status blocks recieved in status_test
* Move sorting to goroutine
* Capitalize constants
* Fix typo
* Use mock reponses in sort test
* Remove byteutils
* Fix ugly format
* Add comment on MultipleValidatorStatus test
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Create entrypoint to run status command, and make unexported functions internal
* Move merge step into FetchAccountStatuses
* Revert service.go
* Remove responseToSortedMetadata
* Simplify mergeTwo
* Replace fmt output with logrus
* Fix typo
* Merge branch 'master' into validator-client-account-statuses
* Update comment
* Merge branch 'validator-client-account-statuses' of https://github.com/michaelhly/prysm into validator-client-account-statuses
* Return error on bad credentials
* Merge branch 'master' into validator-client-account-statuses
* Merge branch 'master' into validator-client-account-statuses
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Skip merge step on error
* Fix conflicts
* Fix mock paths
* Add comments
* Convert some sprintfs to wrapfs
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Rename ExtractPublicKeys to ExtractPublicKeysFromKeyStore and move to account.go
* Add support for keymanager
* Add supported flags to flags list
* Log warning on intermediary errors
* Update output
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Merge branch 'master' into validator-client-account-statuses
* Fix conflicts
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-client-account-statuses
* Merge branch 'validator-client-account-statuses' of https://github.com/michaelhly/prysm into validator-client-account-statuses
* Set context timeout for FetchAccountStatuses
* Remove deprecated grpc.WithTimeout
* gofmt
* Remove getters
* Remove parallel stuff
* Move grpc dialing out of status.go
* Update logging based on feedback
* Update validator/accounts/status.go
2020-05-19 05:13:37 +00:00
Ivan Martinez
aad1b93f70 Optimize slasher handling of duplicate attestations (#5886)
* Move data saving to listener service

* Map result data to attestations to prevent duplicate DB reads

* Gaz

* Fix tests

* Revert "Fix tests"

This reverts commit 499b205a88.

* Revert "Move data saving to listener service"

This reverts commit fd52938dba.

* Gaz

* Undo changes

* Imports

* Reorder parameters

* Fix error log

* Add test for mapReusltsToAtts

* Fix errorf

* Change to safer crypto

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-18 20:50:35 -04:00
Jim McDonald
fe7a123bd9 Allow wallet passphrases to be environment variables (#5879)
* Allow wallet passphrases to be environment variables
* Merge branch 'master' into wallet-env-passphrases
* Namespace environment variables and clear them at the end of the test.
* Merge branch 'master' into wallet-env-passphrases
* Merge branch 'master' into wallet-env-passphrases
* Merge branch 'master' into wallet-env-passphrases
* Merge branch 'master' into wallet-env-passphrases
* Merge branch 'master' into wallet-env-passphrases
* Merge branch 'master' into wallet-env-passphrases
* Merge branch 'master' into wallet-env-passphrases
* Merge branch 'master' into wallet-env-passphrases
* Merge branch 'master' into wallet-env-passphrases
2020-05-18 22:25:36 +00:00
rkapka
2a1a0ce43f Change validator password (#5869)
* Created merge command
* Key merging
* Merge branch 'master' into db-manage-validators
* flag comments
* fixed compilation errors
* added comment to Merge function
* Tested that merging copies keys
* Created command to change password for keys
* Merge branch 'master' into change-validator-password
* Merge branch 'master' into change-validator-password
* cleanup after code review
* Merge remote-tracking branch 'rkapka/change-validator-password' into change-validator-password
* Merge branch 'master' into change-validator-password
* Merge branch 'master' into change-validator-password
* Merge branch 'master' into change-validator-password
* Merge branch 'master' into change-validator-password
2020-05-18 21:35:17 +00:00
terence tsao
c07f1600e9 Prevent parent block with same slot (#5842)
* Block must have a higher slot than parent state
* New tests and existing test
* Typo
* Fixed more existing test....
* Merge branch 'master' into sec0
* Merge branch 'master' into sec0
* Merge branch 'master' of github.com:prysmaticlabs/prysm into sec0
* Update spec tests to v0.11.3
* Merge branch 'sec0' of github.com:prysmaticlabs/prysm into sec0
* Update badge to v0.11.3
* Update badge to v0.11.3
* Merge refs/heads/master into sec0
2020-05-18 20:26:34 +00:00
terence tsao
678347e64b Handle missing archived index (#5899)
* Make `archivedRoot` handle missing root case
* Regression tests
* Fixed existing tests
* Removed debug log
* Merge refs/heads/master into handle-missing-archived-index
* Merge refs/heads/master into handle-missing-archived-index
* More comments on the look back
* Merge branch 'handle-missing-archived-index' of github.com:prysmaticlabs/prysm into handle-missing-archived-index
* Merge refs/heads/master into handle-missing-archived-index
2020-05-18 19:46:06 +00:00
Victor Farazdagi
ca26745720 Implements WRR in init-sync, full bandwidth utilization (#5887)
* implements weighted round robin in init-sync
* protection against evil peer
* reshuffle
* shorten flag
* deterministic order of wrr
* Merge branch 'master' into init-sync-wrr
* Merge refs/heads/master into init-sync-wrr
* Merge refs/heads/master into init-sync-wrr
* allow peers with the same capacity to pe selected at random
* Merge branch 'init-sync-wrr' of github.com:prysmaticlabs/prysm into init-sync-wrr
* adds wrr to e2e tests
* Merge refs/heads/master into init-sync-wrr
* Merge refs/heads/master into init-sync-wrr
* Merge refs/heads/master into init-sync-wrr
2020-05-18 18:59:03 +00:00
Ivan Martinez
52105e6083 Fix silent internet error in prysm.sh (#5877)
* Add check for internet in prysm.sh
* Make script fail
* End script early
* Merge branch 'master' into add-internet-check
* Fix order of ops
* Merge branch 'add-internet-check' of github.com:prysmaticlabs/prysm into add-internet-check
* Merge refs/heads/master into add-internet-check
* Merge refs/heads/master into add-internet-check
* Merge refs/heads/master into add-internet-check
* Merge refs/heads/master into add-internet-check
* Merge refs/heads/master into add-internet-check
* Merge refs/heads/master into add-internet-check
* Merge refs/heads/master into add-internet-check
* Add check for internet to bat script
* Merge branch 'add-internet-check' of github.com:prysmaticlabs/prysm into add-internet-check
* Merge refs/heads/master into add-internet-check
2020-05-18 18:30:19 +00:00
Nishant Das
eb77f56d8a Sort Blocks Before Returning them To Peer (#5894)
* add tests and check
* lint
* Merge refs/heads/master into sortBlocks
2020-05-18 17:58:20 +00:00
Nishant Das
e16f384286 fix (#5893)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-18 20:16:27 +08:00
Ivan Martinez
5d8b5a3c30 Remove DB check for receiving p2p slashings (#5892)
* Removes DB check for receiving p2p slashings
* Fix bad logic
* Merge refs/heads/master into p2p-remove-db-check
* Whoops
* Merge branch 'p2p-remove-db-check' of github.com:prysmaticlabs/prysm into p2p-remove-db-check
2020-05-18 07:36:37 +00:00
Nishant Das
5bb9278a88 make them debug (#5891) 2020-05-18 02:27:18 -04:00
terence tsao
343bee35bc Make SlotsPerArchivedPoint configurable (#5888)
* Make slots per archived point configurable

* 256 -> 2048

* Use beaconconfig
2020-05-17 16:40:41 -04:00
Nishant Das
590016085d More Verbose Logs for Incoming Blocks (#5884)
* add logging
* truncate root
2020-05-17 09:07:21 +00:00
Victor Farazdagi
d79950ab3b Optimizes FSM event triggering (#5881)
* Optimizes machine triggering
* updates queue
* Merge branch 'master' into init-sync-fsm-optimizations
* gazelle
* Merge branch 'init-sync-fsm-optimizations' of github.com:prysmaticlabs/prysm into init-sync-fsm-optimizations
2020-05-16 20:26:00 +00:00
terence tsao
337ae6941f Enhancing block tree viewer (#5880) 2020-05-16 12:29:21 -07:00
Nishant Das
150f8beccd Revert "Add cache to Eth1 RPC functions (#5347)" (#5876)
* Revert "Add cache to Eth1 RPC functions (#5347)"

This reverts commit 159ef3d702.
2020-05-16 02:56:09 +00:00
Raul Jordan
8b168aa450 Add RPC Debug Server, Toggle Logging via gRPC (#5873)
* add in rpc debug server
* sets the valid debug level
* builds
* make post
* Merge branch 'master' into debuglog
* Merge refs/heads/master into debuglog
* caps
* Merge branch 'debuglog' of github.com:prysmaticlabs/prysm into debuglog
* comment
2020-05-15 21:54:53 +00:00
Victor Farazdagi
1cc7d67025 Adds rate limiting tests to beaconBlocksByRangeRPCHandler (#5866)
* overflow/nooverflow tests
* formatting
* check peer disconnecting
* more tests
* Merge branch 'master' into sync-rate-overflow-tests
* formatting
* Merge branch 'sync-rate-overflow-tests' of github.com:prysmaticlabs/prysm into sync-rate-overflow-tests
2020-05-15 20:51:23 +00:00
Raul Jordan
272f794868 Add Suggestion to Paste in Deposit Data into Prylabs/Participate (#5872)
* added instructions for account
2020-05-15 20:24:25 +00:00
terence tsao
5515c20ffd Add skip-regen-historical-states flag (#5871)
* Add feature flag

* Comments to clairfy a few things

* Use feature flag

* Update state gen resume

* More comments

* Remove from dv
2020-05-15 14:49:13 -05:00
Ivan Martinez
9333ede9a1 Unify generated mocks into shared/mock (#5862)
* Add validator mocks to script

* Add more mocks

* Generate all the mocks for Ivan

* Change script to use relative paths and gofmt

* bazel

* Remove duplicates

* Remove duplicated interfaces

* change to shared/mock

* Fix script and build

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-05-15 12:27:46 -05:00
Nishant Das
320bb46f35 More Handshake Cleanup (#5863)
* change to debug log

* disconnect on wrong fork

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-15 11:08:42 -05:00
Raul Jordan
007a98b711 Fix Stream Duties Server + Get Duties Before ChainStart (#5849)
* beacon node stream duties fixes

* comment

* fix critical seconds bug

* back to 12

* config changes

* Update beacon-chain/sync/initial-sync/service.go

* revert config

* Update beacon-chain/rpc/validator/assignments.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
2020-05-15 10:25:43 -05:00
Victor Farazdagi
f461f586a1 Refactors redundant global variables from sync (#5860)
* refactors global variables from sync
* gazelle
* Merge branch 'master' into sync-remove-globals
* better spacing
* Merge branch 'sync-remove-globals' of github.com:prysmaticlabs/prysm into sync-remove-globals
* Merge branch 'master' into sync-remove-globals
2020-05-15 08:53:19 +00:00
Ivan Martinez
52c302307a Remove out of date scripts and fix mockgen script (#5859) 2020-05-14 17:11:52 -05:00
Michael Huang
a7b441270d Update GetValidatorPerformance to support validator indices (#5687)
* add test for stream duties
* rem gomock
* Merge branch 'master' into stream-duties
* context cancelation test
* use interface for epoch ticker in duties
* fix build
* compute duties on first call
* pass tests for streams
* gaz
* ss stream duties
* Merge branch 'master' into stream-duties
* ensure only stream across epoch-wide reorgs
* regen mock for validator
* Update beacon-chain/blockchain/head.go
* Update RPC method GetValidatorPerformance to use validator indices
* Merge refs/heads/master into stream-duties
* Merge refs/heads/master into stream-duties
* Update beacon-chain/rpc/validator/server.go
* Merge branch 'master' into stream-duties
* Update commit hash for com_github_prysmaticlabs_ethereumapis
* Aggregate validator indices before appending performance summaries
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-performance-by-indices
* Merge stream-duties
* Make function more test friendly
* Add indices tests
* fixup
* Fix conflicts
* Update gateway max resv size to 16MB (#5756)

* Update max resv size to 16MB
* Merge refs/heads/master into 5752
* Use GrpcMaxCallRecvMsgSizeFlag for beacon node
* Merge branch '5752' of github.com:prysmaticlabs/prysm into 5752
* Typo
* Fix server
* Merge refs/heads/master into 5752
* Merge refs/heads/master into 5752
* Merge refs/heads/master into 5752
* Merge refs/heads/master into 5752
* Update beacon-chain/gateway/server/main.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/master into 5752
* Rebase to origin/master
* Rebase to origin/master
* Merge remote-tracking branch 'origin/master' into validator-performance-by-indices
* Apply suggestions from code review
* Merge branch 'master' into validator-performance-by-indices
* Fix conflict
* fixup
* Fix tests
* Revert workspace file
* gofmt
* Revert executable permissions on beacon-chain/rpc/beacon/validators.go
* Merge branch 'master' into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
* Add SyncChecker to tests
* Merge branch 'master' into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
* Update beacon-chain/rpc/beacon/validators_test.go
* Update beacon-chain/rpc/beacon/validators_test.go
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-performance-by-indices
* Add comment
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
* Merge branch 'master' into validator-performance-by-indices
2020-05-14 20:52:42 +00:00
terence tsao
2f27966b44 Fix state gen migration (#5858)
* Remove useless `currentSplitSlot == 0`
* Increase slots per archived point to 2048
* Don't delete last archived state
* Revert back to 256
* Merge branch 'master' of github.com:prysmaticlabs/prysm into fix-migration-delete-latest-state
* Don't delete last archived state
* Regression test
* Revert
2020-05-14 20:03:14 +00:00
Ivan Martinez
7a8e85af9e Add testing for EnableFieldTrie in state_trie.go (#5820)
* Add testing for EnableFieldTrie
* Merge branch 'master' into test-field-trie
* Merge branch 'master' into test-field-trie
* Merge refs/heads/master into test-field-trie
* goimports
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Merge refs/heads/master into test-field-trie
* Add tests for generic HTR
* Merge refs/heads/master into test-field-trie
2020-05-14 17:38:34 +00:00
Ivan Martinez
6e9839f987 Validate slashings upon pool exit (#5848)
* Validate slashings upon pool exit
* Change in implementation
* Fix test
* Merge branch 'master' into validate-slashing
* Merge refs/heads/master into validate-slashing
* Merge refs/heads/master into validate-slashing
* Merge refs/heads/master into validate-slashing
* Undo e2e changes
* Merge branch 'validate-slashing' of github.com:prysmaticlabs/prysm into validate-slashing
* Merge refs/heads/master into validate-slashing
2020-05-14 17:11:28 +00:00
terence tsao
f6d8633965 Revert "Check Whether Block Is Already Processed" (#5856)
* Revert "Check Whether Block Is Already Processed (#5850)"

This reverts commit 7630f1852f.
2020-05-14 16:37:58 +00:00
Nishant Das
20c2d78731 add new methods and tests (#5852)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-14 22:44:03 +08:00
Nishant Das
7630f1852f Check Whether Block Is Already Processed (#5850)
* check for missing blocks
* error log
* add test
* fix lint
* fix test
* terence's review
* do not mess with on block
* Merge refs/heads/master into addCheck
2020-05-14 14:11:35 +00:00
Victor Farazdagi
471779e4fc Fixes bug with excessive rate limiting (#5853)
* fixes bug with excessive rate limiting
2020-05-14 13:43:36 +00:00
Nishant Das
34c02ffd34 Allow a Larger Allowance for Peer Faults (#5847)
* allow larger allowance
* change to 5
* Merge branch 'master' into allowLargerAllowance
* test
2020-05-14 03:08:58 +00:00
Preston Van Loon
f831a799c5 Ensure proper block slot for process block header (#5846)
* Ensure proper block slot
* Merge refs/heads/master into extra-validation
2020-05-14 00:31:58 +00:00
terence tsao
dc20f3d72b Regen historical using ArchivedPointRoot then State (#5845)
* Regen from ArchivedPointRoot and State
* Merge branch 'master' into fix-regen-historical-states
2020-05-14 00:10:36 +00:00
terence tsao
70c6dbeb68 Delay atts until subsequent slot (#5833) 2020-05-13 15:46:39 -07:00
terence tsao
8ce01acbcf Check seed before shuffle (#5841) 2020-05-13 14:25:36 -07:00
Shay Zluf
ffa08f5a85 Stream p2p agg attestation (#5809)
* stream aggreagted attestations from p2p network to indexed attestation stream

* remove excessive log

* fix test

* handle nil attestation as well

* Update beacon-chain/sync/subscriber_beacon_aggregate_proof.go

* Update beacon-chain/sync/subscriber_beacon_aggregate_proof.go

* Update beacon-chain/sync/subscriber_beacon_aggregate_proof_test.go

* terence feedback

* sort imports

* sort imports

* Change to received buffer

* preston feedback

* error log

* raul feedback

* more logging changes

* fix duplicate package name

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
2020-05-13 12:21:53 -05:00
Nishant Das
08762af5a2 Revert "Use A Single State in Sync (#5764)" (#5837)
This reverts commit d5f43a8214.
2020-05-13 19:57:59 +08:00
Ivan Martinez
ca7e057ca7 Move cheaper operations earlier into code path (#5835)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-13 14:37:24 +08:00
Raul Jordan
578703fa05 Properly Divide SecondsPerSlot Into Milliseconds (#5821)
* use util for dividing slot durations

* fix places with dividing slot duration

* more dividers fixed

* format import

* fix formatting in validator test

* fix slot test tolerance

* nishant suggestions

* imports

* resolve e2e

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-13 11:28:17 +08:00
Nishant Das
d5f43a8214 Use A Single State in Sync (#5764)
* change this stuff

* Update beacon-chain/blockchain/process_block_helpers.go

* Update beacon-chain/blockchain/process_block_helpers.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-05-13 07:49:15 +08:00
Ivan Martinez
6488ab4a26 Add fast function for comparing attestation data (#5834)
* Add function for comparing attestation datas

* Fix imports

* Apply beneficial spots

* Gaz
2020-05-12 16:55:17 -04:00
Ivan Martinez
cd1a4f18f4 Fix historical detection for the slasher (#5831)
* Fix historical detection for the slasher
* More fixes
* Fix
* Run historical detection sequentially
* Add context err handler
* Add return
* Fixes
* Merge branch 'master' into slasher-fixes
2020-05-12 18:32:42 +00:00
terence tsao
9ffc6b71d6 Update spec tests to v0.11.2 (#5832) 2020-05-12 12:44:17 -05:00
Connor Stein
4242581f1e Test EnterPassword function in shared/cmd (#5822)
* test

* fix golint

* more lint

* gazelle

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-05-12 10:01:02 -05:00
Nishant Das
ab23fadc5e Revert Change Added in #5811 (#5828)
* revert

* remove
2020-05-12 21:39:36 +08:00
Victor Farazdagi
baf9ec60eb Adds BlockBatchLimitBurstFactor flag (#5825)
* adds BlockBatchLimitBurstFactor flag
* Merge branch 'master' into burst-factor-flag
2020-05-12 11:31:10 +00:00
Victor Farazdagi
79ce15df63 Removes deprecated flag from config (#5824)
* removes deprecated flag from config
2020-05-12 10:53:24 +00:00
terence tsao
96219fc9fa Add metric for reorg count (#5819)
* Add reorg counter metric
* Merge branch 'master' into reorg-metric
* Merge branch 'master' into reorg-metric
2020-05-12 05:48:16 +00:00
Nishant Das
edfb32021b Validate Finalized Root in Status RPC Requests (#5811)
* additional status validation

* changes

* clean up

* Update beacon-chain/db/kv/finalized_block_roots.go

* Update beacon-chain/sync/rpc_status.go

* Update beacon-chain/sync/rpc_status.go

* Update beacon-chain/sync/rpc_status.go

* terence's review

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-12 11:22:01 +08:00
Preston Van Loon
40591924c2 Add attestation inclusion histogram (#5818)
* Add attestation inclusion histogram
* Merge branch 'master' into attestaiton-inclusion-histogram
2020-05-12 02:00:42 +00:00
Ivan Martinez
946a2caafd Add fix for nil state in InitializeFromProto (#5817)
* Add nil check and tests
* Add unsafe test
* Update tools/genesis-state-gen/main.go
* Undo genesis state gen changes
* Merge branch 'proto-fuzz-fix' of github.com:prysmaticlabs/prysm into proto-fuzz-fix
* gaz
* Fix
2020-05-12 00:23:05 +00:00
terence tsao
b5e7f9dd6d Run go fmt in prysm (#5815)
* go fmt
2020-05-11 22:03:15 +00:00
terence tsao
4c9ff7012c Reduce state copies for SubmitAggregateSelectionProof (#5813)
* `GetValidatorPerformance` return `Unavailable` when syncing
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Reduce state copies for SubmitAggregateAndProof
* Merge branch 'master' into reduce-state-copies
2020-05-11 16:21:34 +00:00
Raul Jordan
42278359d9 Add Docker Image for Genesis State Generator (#5697)
* add test for stream duties
* rem gomock
* Merge branch 'master' into stream-duties
* context cancelation test
* use interface for epoch ticker in duties
* fix build
* compute duties on first call
* pass tests for streams
* gaz
* ss stream duties
* Merge branch 'master' into stream-duties
* ensure only stream across epoch-wide reorgs
* regen mock for validator
* Update beacon-chain/blockchain/head.go
* Merge refs/heads/master into stream-duties
* Merge refs/heads/master into stream-duties
* Update beacon-chain/rpc/validator/server.go
* Merge branch 'master' into stream-duties
* add docker
* gaz
* update workspac
* Merge branch 'stream-duties' into state-gen-docker
* pure off
* Merge branch 'state-gen-docker' of github.com:prysmaticlabs/prysm into state-gen-docker
* gen
* base img
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* fix confs
* fix up confs
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
* Merge refs/heads/master into state-gen-docker
2020-05-11 12:00:42 +00:00
Nishant Das
1110a5caab minor fix (#5810) 2020-05-11 19:36:42 +08:00
Nishant Das
6840afb45e Fix Issues With Peer Handshakes (#5799)
* add check

* make handshake better

* fix a lot of things

* Update beacon-chain/p2p/handshake.go

* Update beacon-chain/p2p/handshake.go

* fix things

* fix

* fix handshake

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-11 12:29:23 +08:00
terence tsao
34f28a31b1 No magic number for BlockBodyRoot (#5803)
* `GetValidatorPerformance` return `Unavailable` when syncing

* Use proper config values for BlockBodyRoot

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-11 11:45:31 +08:00
Preston Van Loon
bfe694c4f3 Check for pending deposits and exit early, if possible (#5802)
* Check for pending deposits and exit early, if possible
2020-05-11 02:38:41 +00:00
terence tsao
c000509bdb GetValidatorPerformance return Unavailable when syncing (#5795) 2020-05-10 13:08:45 -07:00
Victor Farazdagi
e53452a437 Moves connectPeers to common test setup file (#5800)
* moves connectPeers
2020-05-10 14:47:05 +00:00
Nishant Das
aeb6dc13ac Add Ability to Restrict Outbound Dials (#5794)
* blacklist cidr
* add test
* Merge refs/heads/master into p2pBlacklist
2020-05-09 22:18:21 +00:00
Ivan Martinez
c82f2d5657 Fix test setup and change participation min back to 100% (#5791)
* Increase time for test to start

* Try anothre fix

* Set minimum participation back to 100%

* Change bnode count to 2

* Give extra wiggle room for metrics

* Remove comment
2020-05-09 15:11:10 -05:00
terence tsao
419343123a Fix e2e flakynes for new state mgmt (#5790) 2020-05-08 21:56:51 -07:00
Nishant Das
a25354adf0 Remove ETH1 Data Vote Cache (#5792)
* remove cache
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into removeETH1DataCache
* remove everything
2020-05-09 04:08:24 +00:00
Ivan Martinez
26eead0d1c Gate disable lookback behind featureflag (#5782)
* Gate disable lookback behind featureflag
* Merge branch 'master' into slasher-lookback-flag
* Update shared/featureconfig/config.go
* Merge branch 'master' into slasher-lookback-flag
* Add context timeout error handling
* Merge branch 'slasher-lookback-flag' of github.com:prysmaticlabs/prysm into slasher-lookback-flag
* gaz
* Merge branch 'master' into slasher-lookback-flag
* Merge branch 'master' into slasher-lookback-flag
* Merge refs/heads/master into slasher-lookback-flag
* Merge refs/heads/master into slasher-lookback-flag
* Merge refs/heads/master into slasher-lookback-flag
* Merge refs/heads/master into slasher-lookback-flag
2020-05-09 02:07:37 +00:00
Preston Van Loon
c6cac96a3b Duplicate init sync test target for better coverage reporting (#5789)
* duplicate target for better coverage testing
* Merge refs/heads/master into init-sync-raceoff
2020-05-09 01:40:14 +00:00
Preston Van Loon
87e0fe5928 Refactor ReceiveBlock to receive the block root. (#5785)
* refactor ReceiveBlockNoPubsub to receive block root
* Refactor ReceiveBlock to receive block root
* A few other minor refactoring to reduce block HTR
* use arg, remove HTR
* more slight refactoring, comments
* fix test build
* Merge refs/heads/master into receive-with-root
* Merge refs/heads/master into receive-with-root
2020-05-09 01:22:59 +00:00
Nishant Das
5b134239e3 Make IP Static for Public IPs (#5788)
* don't use endpoint predictor
* Merge branch 'master' into staticIP
* Merge refs/heads/master into staticIP
2020-05-09 00:58:11 +00:00
terence tsao
c590029e48 Temporarily remove new state mgmt from e2e (#5786)
* Temporarily remove new state mgmt from e2e
2020-05-09 00:28:06 +00:00
Preston Van Loon
b00bbfeec7 Release enableCustomBlockHTR to all (#5742)
* Release deprecatedEnableCustomBlockHTR to all

* Release deprecatedEnableCustomBlockHTR to all

* Fix builds

* Treat nil body as empty

* Use custom HTR in signing root

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-08 13:50:39 -07:00
terence tsao
7a27d89e68 Reduce memory usage for new-state-mgmt at init sync (#5778)
* Add `GetWithoutCopy`
* Add `StateByRootInitialSync`
* Use `StateByRootInitialSync` for initial syncing using new-state-mgmt
* Merge branch 'master' into new-state-init-sync-mem
* Skip if split slot is 0
* Merge branch 'new-state-init-sync-mem' of github.com:prysmaticlabs/prysm into new-state-init-sync-mem
* Make sure we invalidate cache
* Add test part 1
* Add tests part 2
* Update beacon-chain/cache/hot_state_cache.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
* Comment
* Merge branch 'new-state-init-sync-mem' of github.com:prysmaticlabs/prysm into new-state-init-sync-mem
* Merge branch 'master' of github.com:prysmaticlabs/prysm into new-state-init-sync-mem
* Dont need to run fork choice and save head during intial sync
* Invalidate cache at onBlockInitialSyncStateTransition
* Merge branch 'new-state-init-sync-mem' of github.com:prysmaticlabs/prysm into new-state-init-sync-mem
* Revert saveHeadNoDB changes
* Add back DeleteHotStateInCache
* Removed extra deletion
* Merge branch 'master' of github.com:prysmaticlabs/prysm into new-state-init-sync-mem
* Proper set splitslot for tests
* Merge branch 'master' into new-state-init-sync-mem
* Merge branch 'master' of github.com:prysmaticlabs/prysm into new-state-init-sync-mem
* Merge branch 'new-state-init-sync-mem' of github.com:prysmaticlabs/prysm into new-state-init-sync-mem
2020-05-08 19:02:48 +00:00
Ivan Martinez
ad8716a58e Refactor validator protection for attesters (#5695)
* Finish refactor for attestation protection

* Finish refactor for proposal history

* Revert "Finish refactor for proposal history"

This reverts commit 2f13720063.

* Fix tests

* Implement UpdateProtections

* Implement refactor

* Fixes

* fix

* Undo proposer changes

* Fix test

* Final look through

* Add tests for protections function

* Add lock

* Add flag in front of attester protection code

* Add proper rwlocks and fix flags

* fix

* fix build

* Fix atestation tests

* Fix deprecated flags

* Add protect attester to standard attesting test

* Remove comment

* gofmt

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-08 10:16:53 -05:00
Ivan Martinez
03c7a6c0e2 Validator status improvements and fix (#5775)
* Validator status optimization and bug fix

* Remove uneeded state check

* Change val function to read only

* Change to read only

* Undo error change

* Undo deposit change
2020-05-08 10:04:01 -04:00
Nishant Das
6fed51d380 Don't Copy The Whole Validator Map each time (#5780)
* fix copying issues

* revert some changes
2020-05-08 18:14:18 +08:00
Shay Zluf
c1a8b41347 Is slashable block rpc endpoint implementation (#5765)
* is slashable block rpc endpoint implementation

* add span

* raul feedback

* fix error

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-08 08:51:56 +03:00
Preston Van Loon
63e2e8acd7 Use alpine base image including libstdc++ (#5777)
* fix #5768 with an alpine base including libstdc++
* Merge branch 'master' into fix-docker-alpine
2020-05-07 22:01:48 +00:00
Ivan Martinez
9a1157465e Change non-mutating validator accesses to ReadOnly (#5776)
* Change instances of ValidatorAtIndex to ReadOnly where possible

* Use ReadOnly for VerifyExit and Slashings

* Move length check to before lock

* Improve readonly tests

* undo process attester changes

* Fix test
2020-05-07 14:15:51 -04:00
Ivan Martinez
574bf3deac Clean usage of cli.context in validator/node (#5758)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-07 10:14:08 -05:00
Victor Farazdagi
40c29744e3 Init-sync discard debug logs in tests (#5774)
* refactors block fetching function to fetcher
* more comments fixed
* Merge branch 'master' into init-sync-optimizations
* moves helper code into separate file
* move test setup code to testmain
* removes bench
2020-05-07 13:13:45 +00:00
Victor Farazdagi
f0c0ed80cb BLS code cleanup (#5773)
* removes unused code
* add specs comments
* removes unused VerifyAggregate
* fixes benchmark test
* Merge branch 'master' into blc-cleanup
* updates benchmark test
* Merge branch 'master' into blc-cleanup
2020-05-07 12:05:53 +00:00
Nishant Das
f6090d0a38 Update Bootnode to v0.11.2 (#5767)
* update to v0.11.2

* fix test

* docker

* Update BUILD.bazel

* Update BUILD.bazel

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-07 18:50:03 +08:00
Preston Van Loon
87c3599c33 Update BLS and use constant for SetETHmode (#5772)
* Update BLS and use constant for SetETHmode
2020-05-07 07:49:24 +00:00
Ivan Martinez
4d9da25d02 Add confirm password to validator accounts create (#5762)
* Add confirm password to accounts create

* Fix build

* Update shared/cmd/helpers.go

* Update shared/cmd/helpers.go

Co-authored-by: Shay Zluf <thezluf@gmail.com>

* Change to return empty ""

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: Shay Zluf <thezluf@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-06 19:50:19 -04:00
Ivan Martinez
b2ee466f79 Add--disable-historical-detection flag to slasher (#5759)
* Add--disable-historical-detection flag
* Merge branch 'master' into slasher-add-hist-flag
* Fix for comments
* Add flag to usage help
* Merge branch 'master' into slasher-add-hist-flag
* Update slasher/usage.go
* Fix imports
* Merge branch 'master' into slasher-add-hist-flag
* Merge branch 'master' into slasher-add-hist-flag
* Merge branch 'master' into slasher-add-hist-flag
2020-05-06 22:17:36 +00:00
Victor Farazdagi
c4eb8c7a16 Refactors block fetching function to fetcher (#5766)
* refactors block fetching function to fetcher
* more comments fixed
* Merge refs/heads/master into init-sync-upd
* Merge refs/heads/master into init-sync-upd
* Merge refs/heads/master into init-sync-upd
2020-05-06 21:29:50 +00:00
terence tsao
38f2ec6d7d Update gateway max resv size to 16MB (#5756)
* Update max resv size to 16MB
* Merge refs/heads/master into 5752
* Use GrpcMaxCallRecvMsgSizeFlag for beacon node
* Merge branch '5752' of github.com:prysmaticlabs/prysm into 5752
* Typo
* Fix server
* Merge refs/heads/master into 5752
* Merge refs/heads/master into 5752
* Merge refs/heads/master into 5752
* Merge refs/heads/master into 5752
* Update beacon-chain/gateway/server/main.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/master into 5752
2020-05-06 21:01:23 +00:00
terence tsao
ef4dead3fe Fix cold state generation (#5770) 2020-05-06 13:25:37 -07:00
Raul Jordan
d5b1f9f1f9 Implement Stream Duties Functionality (#5685)
* add test for stream duties

* rem gomock

* context cancelation test

* use interface for epoch ticker in duties

* fix build

* compute duties on first call

* pass tests for streams

* gaz

* ss stream duties

* ensure only stream across epoch-wide reorgs

* regen mock for validator

* Update beacon-chain/blockchain/head.go

* Update beacon-chain/rpc/validator/server.go

* update workspac

* pregenesis check

* tests pass

* build fix

* Revert "tests pass"

This reverts commit 9029d63ef3.

* ethereumapis

* gaz

* Update beacon-chain/rpc/validator/assignments.go

* test for reorg

* fix up required tests

* fmt

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
2020-05-06 14:15:31 -05:00
Ivan Martinez
67a2698463 Remove flag requirement from accounts keys (#5757)
* Remove flag requirements for keystore-path and password

* Add test for HandleEmptyFlags

* Add comment

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-06 01:55:25 -04:00
Nishant Das
ae66f63ec2 Memory Improvements (#5760)
* fix methods
* fix path for only initial sync
* update comment
* Merge refs/heads/master into memImprovements
2020-05-06 05:04:02 +00:00
Nishant Das
bf2a37b27f Remove Old Sync Routine (#5761)
* remove old sync
2020-05-06 04:36:34 +00:00
terence tsao
aea7a8d291 Future slot check for state end point (#5755) 2020-05-05 18:42:11 -07:00
Raul Jordan
840bfc5f6b Add Chain Config File for Validator (#5751)
* builds for config file
2020-05-05 22:19:27 +00:00
terence tsao
f29ea77a14 Update to v0.11.2 badge (#5750)
* Update to v0.11.2 badge
* Merge branch 'master' into terencechain-patch-1
2020-05-05 20:36:53 +00:00
Ivan Martinez
2b7865cb3b Move "Enter a password" cmd instructions to shared/cmd (#5724)
* Move EnterPassword CMD to cmd package

* Add comment

* Add tracking issue and remove log.Fatal

* Add better error handling

* gaz

* Comment fix

* Update shared/cmd/helpers.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-05-05 16:13:18 -04:00
Nishant Das
3a677ef342 Add Persistent Subnets (#5734)
* add params

* add changes

* bug fixes

* fix method

* get new assignments

* add test and comments

* change to slice of uint64

* add test

* lint

* Update beacon-chain/rpc/validator/assignments_test.go

* Update beacon-chain/cache/committee_ids.go

* Update beacon-chain/rpc/validator/assignments.go

* add comment

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-05-05 14:26:20 -05:00
Shay Zluf
1a27c21d9c Load chain config from file (#5694)
* load chain config from file

* revert flag name change

* add dependencies to image

* Update shared/cmd/flags.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>

* Update beacon-chain/main.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>

* added test to load config file

* Merge branch 'yaml_chain_config' of github.com:prysmaticlabs/prysm into yaml_chain_config

# Conflicts:
#	beacon-chain/main.go

* replace hex with yaml format of fixed byte array

* fix test and check if comment

* move to node package

* gaz

* added contract address case

* fix key name issue

* add tests

* gaz

* add 1 byte handling

* change to fatal

* add config printout

* revert main changes

* revert line removal

* fix one byte handling

* fix test and one byte handling

* remove log

* Apply suggestions from code review

* change to debug

* Update beacon-chain/node/node.go

* move helper methods

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-05-05 20:58:07 +03:00
Victor Farazdagi
45f2447e6a More explicit error message on wrong process when running prysm.sh (#5747)
* exit when incorrect command passed
* more explicit error message
* grammar
2020-05-05 13:23:09 +00:00
Nishant Das
2eac24cb79 Retry Initialization of ETH1 Connection (#5730)
* retry failures
* Merge branch 'master' into retryInitialization
* fix test
* Merge branch 'retryInitialization' of https://github.com/prysmaticlabs/geth-sharding into retryInitialization
* Merge refs/heads/master into retryInitialization
* Merge refs/heads/master into retryInitialization
* Merge refs/heads/master into retryInitialization
* Merge refs/heads/master into retryInitialization
* Merge refs/heads/master into retryInitialization
* Merge refs/heads/master into retryInitialization
* fix method
* Merge branch 'retryInitialization' of https://github.com/prysmaticlabs/geth-sharding into retryInitialization
* Merge refs/heads/master into retryInitialization
* Merge refs/heads/master into retryInitialization
* Merge refs/heads/master into retryInitialization
* Merge refs/heads/master into retryInitialization
2020-05-05 09:06:43 +00:00
Victor Farazdagi
bbde2a6820 Assert no side effects occur on test (#5714)
* add reset funcs
* init -> TestMain for beacon config params
* fixes build file
* core/epoch spectests updated
* core/blocks spectests updated
* fix the rest of spectests
* SetupTestConfigCleanup
* revert copy() api
* rever all cases of copy()
* fixes spectests
* updates fork_test
* config_test update
* fixes spectest/config_test
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge branch 'master' into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge branch 'master' into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
2020-05-05 08:39:38 +00:00
Nishant Das
0b8ee54076 Add More Flags To Dev Mode (#5744)
* add flags
* Merge refs/heads/master into addDevFlags
* Merge refs/heads/master into addDevFlags
2020-05-05 08:00:56 +00:00
Preston Van Loon
eb2abbdd8b libfuzz based tests (#5095)
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* use opt for fuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge branch 'go-1.14-libfuzz' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* use ubuntu as the default build image
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge branch 'master' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Move fuzz tests
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge branch 'go-1.14-libfuzz' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* making progress on p2p fuzz
* Merge branch 'go-1.14-libfuzz' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* use a single stream repeatedly
* use a single stream repeatedly
* use many streams
* fixes
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge branch 'master' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Merge branch 'master' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Add basic test for ssz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge branch 'master' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge branch 'master' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Use a custom go_library to add libfuzzer
* delete old corpus, fix rpc_status_fuzz
* move fuzz.bzl
* minor fixes
* Merge branch 'go-1.14-libfuzz' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* add c-shared library (doesnt work)
* Merge branch 'go-1.14-libfuzz' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* fix build
* fixes
* Merge refs/heads/master into go-1.14-libfuzz
* lint
* more lint
* Merge branch 'go-1.14-libfuzz' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* more lint
* allow environment variable
* Merge refs/heads/master into go-1.14-libfuzz
* Add a fuzzit image with the beacon_states
* Merge branch 'go-1.14-libfuzz' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* lint
* readme
* lint
* fix lint again i think
* gaz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* breakup deps
* Merge branch 'go-1.14-libfuzz' of github.com:prysmaticlabs/prysm into go-1.14-libfuzz
* don't panic on failure
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* panic if no beacon states to read
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* update rules_foreign_cc
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* remove c_shared target, manually tag tests
* Add readme to fuzz package
* delete a few comments
* delete a few comments
* lint
* gaz
* gaz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
* Merge refs/heads/master into go-1.14-libfuzz
2020-05-05 07:22:26 +00:00
Preston Van Loon
eb27f35982 Use the custom HTR in a few more places (#5743) 2020-05-05 14:42:53 +08:00
Shay Zluf
9ea3f58a5e Verify sig slasher (#5661)
* first cherry pick

* second

* new endpoint

* fork digest by epoch

* fork and sig verify

* fix test

* fix comment

* gaz

* remove unused param

* remove space

* moved to shared attestation_utils.go

* raul comment

* gaz

* goimports

* fix import cycle

* fix test

* shorter helper method

* add another helper function

* fix comment

* param fix

* gaz

* fix error

* Update beacon-chain/core/blocks/block_operations.go

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>

* update pseudocode

* remove teardown

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
2020-05-05 08:15:32 +03:00
Preston Van Loon
9be8a456eb Use stateutil.BlockRoot everywhere (#5739)
* Sweeping replace of ssz.HashTreeRoot(block) to stateutil.BlockRoot, minor tweaks to critical path of proposeBlock
* imports
* Merge branch 'master' into better-block-htr
* Add --enable-custom-block-htr to e2e flags
* Merge branch 'better-block-htr' of github.com:prysmaticlabs/prysm into better-block-htr
2020-05-05 04:30:24 +00:00
terence tsao
4958c0372c Add sent block time metric (#5738) 2020-05-04 19:00:00 -07:00
Shay Zluf
1fa495afc1 Add params and update spec param names (#5732)
* add params and update names
* Merge branch 'master' into update_params
* Merge refs/heads/master into update_params
2020-05-05 00:14:43 +00:00
terence tsao
e8da03a6b2 Use AttestationPreState (#5737) 2020-05-04 18:48:14 -05:00
Ivan Martinez
d3cb4b3059 Log out public key with accounts create (#5723)
* Log public key with deposit data
* Merge refs/heads/master into log-pub-deposit
* Merge refs/heads/master into log-pub-deposit
* Merge refs/heads/master into log-pub-deposit
* Merge refs/heads/master into log-pub-deposit
* Merge refs/heads/master into log-pub-deposit
* Update validator/accounts/account.go

Co-authored-by: Nishant Das <nishdas93@gmail.com>
2020-05-04 15:00:35 +00:00
Victor Farazdagi
140aff4398 fixes runtime panic in state/getters (#5728)
* fixes runtime panic in state/getter
* Merge branch 'master' into check-non-nil-in-state-getter
* return empty map
* Merge branch 'check-non-nil-in-state-getter' of github.com:prysmaticlabs/prysm into check-non-nil-in-state-getter
2020-05-04 10:15:33 +00:00
Ivan Martinez
c614412885 Remove silent errors from slasher (#5722)
* Remove silent errors from slasher
* Merge refs/heads/master into slasher-silent-errors
* Merge refs/heads/master into slasher-silent-errors
* Merge refs/heads/master into slasher-silent-errors
2020-05-04 08:17:18 +00:00
Nishant Das
1432332923 Return Genesis Block (#5709)
* add check
* lint
* lint
* Merge branch 'master' into returnGenesis
* Merge refs/heads/master into returnGenesis
* Merge refs/heads/master into returnGenesis
* Merge refs/heads/master into returnGenesis
* Merge refs/heads/master into returnGenesis
* Merge refs/heads/master into returnGenesis
* terence's review
* Merge branch 'returnGenesis' of https://github.com/prysmaticlabs/geth-sharding into returnGenesis
* Merge refs/heads/master into returnGenesis
* Merge refs/heads/master into returnGenesis
* fix failing test
2020-05-04 07:54:31 +00:00
Victor Farazdagi
b5c4dc2a75 Refactor db teardown to testing.TB.Cleanup (#5725)
* init-sync updates
* slasher/db/kv tests
* beacon-chain/rpc/beacon tests
* update kv_test
* beacon-chain/rpc-validator tests updated
* slasher/db/kv - remove teardown method
* beacon-chain/sync tests updated
* beacon-chain/db/kv tests updated
* beacon-chain/blockchain tests updated
* beacon-chain/state/stategen tests updated
* beacon-chain/powchain updates
* updates rest of slasher tests
* validator/db tests
* rest of the tests
* minor comments update
* gazelle
* Merge refs/heads/master into teardowndb-to-cleanup
2020-05-04 01:14:34 +00:00
terence tsao
17df25f3d7 Add more domains to domain cache (#5726) 2020-05-03 17:34:25 -07:00
Victor Farazdagi
af5b9222da Re-enable skipped block list paging unit test (#5691)
* unskip on a single shard
* Merge branch 'master' into unskip-block-list-test
* fixes incorrect test state modification
* Merge branch 'master' into unskip-block-list-test
* minor formatting
* Merge branch 'unskip-block-list-test' of github.com:prysmaticlabs/prysm into unskip-block-list-test
* set sharding back to 4
* Merge refs/heads/master into unskip-block-list-test
* Merge refs/heads/master into unskip-block-list-test
* Merge refs/heads/master into unskip-block-list-test
2020-05-02 04:03:50 +00:00
terence tsao
42961277e1 Add histogram metrics for block arrival time (#5708)
* Add metrics to track block propogation delay

* Grammar

* Grammar

* Metrics for block sent

* Refactor into own function

* Removed sent

* Lint

* Use histogram. Thanks Preston for the suggestion!

* s/total/histogram

* Update name to `block_arrival_latency_milliseconds`

* Use milliseconds

* Use unix nano

* Use SlotToTime

* Preston's feedback

* Handle err
2020-05-01 19:35:15 -07:00
terence tsao
973fa9f326 Regen historical state: don't skip saving historical state (#5712)
* Save every state at archived point
* Merge branch 'master' into save-every-state
2020-05-02 00:36:54 +00:00
Preston Van Loon
37f2a04e51 SlotToTime helper (#5710)
* SlotToTime helper
* gofmt
* gaz
* overflow
* Merge refs/heads/master into better-time
* Fix tests, move overflow
* Merge branch 'better-time' of github.com:prysmaticlabs/prysm into better-time
* smaller diff
2020-05-01 23:19:43 +00:00
Ivan Martinez
125d022518 Rename Precompute Balance vars to be more descriptive (#5706)
* Rename p *Balance and some Balance vars
* Rename more
* Fix comments
* Fix typo
* Forgot a rename
2020-05-01 19:43:04 +00:00
Victor Farazdagi
b42cc724c5 Enforce validator's keystore dir (#5707)
* enforces keystore dir
* Merge refs/heads/master into recheck-before-raw-tx-data
* do not ignore error
* Merge branch 'recheck-before-raw-tx-data' of github.com:prysmaticlabs/prysm into recheck-before-raw-tx-data
2020-05-01 15:12:26 +00:00
Ivan Martinez
436d545f80 Move recreated constants out of smaller scopes (#5699) 2020-05-01 06:45:24 -07:00
Nishant Das
2c3f974361 Custom Method For Block Signing Root (#5704)
* custom block signing root

* add comment and test

* Update beacon-chain/core/helpers/signing_root.go

* Update beacon-chain/core/helpers/signing_root.go

* fix changes
2020-05-01 03:37:37 -04:00
Nishant Das
7bea237397 Revert Validator Reference Copy (#5701)
* revert all changes
* revert test
* unreachable code
* Merge refs/heads/master into revertValidatorRefCopy
* Merge refs/heads/master into revertValidatorRefCopy
2020-05-01 02:48:46 +00:00
wgknowles
c877efd90e replaced 265 with 256 ...derp (#5702)
* replaced 265 with 256 ...derp
2020-05-01 02:36:52 +00:00
Raul Jordan
2e33595187 Implement GetBeaconState Endpoint (#5668)
* implement get beacon state
* gaz
* Merge branch 'master' into implement-debug-state
* passing tests
* enable with featureconfig
* struct oder
* Update beacon-chain/rpc/beacon/state.go
* Merge refs/heads/master into implement-debug-state
* lint resolve
* Merge branch 'implement-debug-state' of github.com:prysmaticlabs/prysm into implement-debug-state
* tested at runtime
* fix build
* Merge branch 'master' into implement-debug-state
* Merge refs/heads/master into implement-debug-state
* Merge refs/heads/master into implement-debug-state
* Merge refs/heads/master into implement-debug-state
* Merge refs/heads/master into implement-debug-state
* Merge refs/heads/master into implement-debug-state
* build and fmt
* conf
* Merge refs/heads/master into implement-debug-state
* Merge refs/heads/master into implement-debug-state
* Merge refs/heads/master into implement-debug-state
* Merge refs/heads/master into implement-debug-state
* Merge refs/heads/master into implement-debug-state
2020-05-01 01:47:10 +00:00
Shawki Sukkar
e1ac1d3d80 Log out important directories for validator client (#5653)
* .
* print in beacon-chain, validator and slasher
* add source and build
* fix
* fix
* fix
* fix
* run gazelle
* change log
* change log file
* change log file
* change log message
* change log message
* Merge branch 'master' into Display-key-paths-at-startup
* change the logging code place
* change datadir to out of scoop
* Merge branch 'master' into Display-key-paths-at-startup
* Merge branch 'master' into Display-key-paths-at-startup
2020-04-30 23:17:06 +00:00
terence tsao
fdad7e67b0 Update pubsub seen cache to be per epoch instead of per slot (#5698)
* hasSeenAggregatorIndexSlot -> hasSeenAggregatorIndexEpoch
* Fix test
* Update subscriber
* setSeenCommitteeIndicesSlot -> setSeenCommitteeIndicesEpoch
* Fix test
* Revert "setSeenCommitteeIndicesSlot -> setSeenCommitteeIndicesEpoch"

This reverts commit bd638ae556.
* Fixed unaggregated att seen cache to use per slot
2020-04-30 22:16:14 +00:00
Victor Farazdagi
cc07494e67 shared/keystore: cleanup (#5689)
* fixes inconsistent naming

* removes unused methods

* proper temp keystore cleanup in tests

* more naming fixes

* one more fix of keystore teardown in tests

* more robust teardown
2020-04-30 10:00:37 -05:00
Nishant Das
5f53f9fde1 Clean Up Of Dynamic Subscriptions (#5690)
* fix subscriptions

* add reg test
2020-04-30 09:14:59 -05:00
Nishant Das
3a295fb3ec Fix Voluntary Exits Panic (#5688)
* add fix and regression test
* Update beacon-chain/rpc/validator/exit_test.go

Co-Authored-By: Shay Zluf <thezluf@gmail.com>
* Update beacon-chain/rpc/validator/exit_test.go

Co-Authored-By: Shay Zluf <thezluf@gmail.com>
* Update exit_test.go
2020-04-30 07:57:49 +00:00
Ivan Martinez
2f88174d0d Unify usage of context in slasher client (#5684)
* Unify usage of context in slasher client

* Fix build

* Add error handlers so all processes stop

* Remove unneeded checks
2020-04-29 19:27:01 -04:00
Raul Jordan
546196a6fa Other Package Godocs for Prysm (#5681)
* e2e docs
* slasher docs
* Merge branch 'other-package-godocs' of github.com:prysmaticlabs/prysm into other-package-godocs
* all validator package comments
* Merge branch 'master' into other-package-godocs
* completed all other packages
* Merge branch 'master' into other-package-godocs
* Merge refs/heads/master into other-package-godocs
2020-04-29 21:32:39 +00:00
Nishant Das
4d30519dda fix bugs (#5683) 2020-04-29 14:28:22 -05:00
Victor Farazdagi
2c1e3aa4ee Validator key files: allow symlinks (#5679)
* traverse symlinks
* Merge branch 'master' into account-keys-symlinks
* unit test
* Merge branch 'account-keys-symlinks' of github.com:prysmaticlabs/prysm into account-keys-symlinks
* Merge refs/heads/master into account-keys-symlinks
* removes unncecessary line
* Merge branch 'account-keys-symlinks' of github.com:prysmaticlabs/prysm into account-keys-symlinks
* fixes tests
* better teardown of resources
2020-04-29 18:31:22 +00:00
Raul Jordan
3416962fc2 All Beacon Node Package-Level Godocs (#5677)
* package level godocs fixed

* all beacon node godocs

* comment and gaz

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-29 12:40:33 -05:00
Raw Pong Ghmoa
3fc6afa02e beacon/log: augment logs with block roots (#5675)
* beacon/log: augment synced log with block root and finalized root
* beacon/log: augment initial sync log with block root
* beacon/sync: degrade pending block log to DEBUG level
* beacon/log: restore info level for state transition
* beacon/log: improve info logging
* Merge branch 'master' into q9-log-block
* Merge branch 'master' into q9-log-block
2020-04-29 16:57:04 +00:00
terence tsao
05fcb1073a Remove duplicated sig verification (#5676)
* Remove duplicated sig verification
2020-04-29 15:57:58 +00:00
Nishant Das
81a7bc7e05 Add back State To ComputeProposerIndex (#5674)
* add back state
* fix tests
* change method signatures
* lint
* Merge branch 'master' into addBackState
* Merge branch 'master' into addBackState
* terence's review
* preston's review
* add back comment
2020-04-29 15:22:52 +00:00
Ivan Martinez
84e51a5236 Add prometheus metrics test into E2E (#5673)
* Progress on metrics tests
* Progress on metrics test
* Get metrics E2E working
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into e2e-metrics
* Complete most of metrics tests
* Change E2E polling to the middle of a slot, instead of at the start of the middle
* Add metrics to all E2E
* Remove extra types
* Update endtoend/evaluators/metrics.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge branch 'master' into e2e-metrics
* Add more comments, address feedback
* Merge branch 'e2e-metrics' of https://github.com/prysmaticlabs/prysm into e2e-metrics
* Fix build
* Remove unneeded comment
* Set E2E_EPOCHS back
* Improve sync testing reliability
* Remove metrics check from slashing
* Improve time allotted to sync
* Remove possibly flaky sync test change
2020-04-29 13:42:12 +00:00
Raul Jordan
3b2c514c06 Empty Committee Check in Submit Attestation (#5672)
* empty committee check
* Merge refs/heads/master into validator-id-errs
2020-04-29 02:44:51 +00:00
Raul Jordan
94155191b7 Ensure Single Context Used for Beacon Node Cancelation on SIGTERM (#5671)
* ensure single point of entry for ctx and cancelation of expensive func
2020-04-29 02:28:43 +00:00
terence tsao
5636cd3ed8 More efficient ancestor head retrieval for GetAttestationData (#5669)
* Use `BlockRootAtSlot` to look up historical head root

* Update test

* Typo
2020-04-28 19:44:06 -05:00
terence tsao
44611e0fb2 A tool to update genesis time of an existing state (#5664)
* Add a tool to update genesis time
* Minor touchups
* Merge branch 'master' into update-genesis-time
* Added a readme
* Merge refs/heads/master into update-genesis-time
* Merge branch 'update-genesis-time' of github.com:prysmaticlabs/prysm into update-genesis-time
* Merge refs/heads/master into update-genesis-time
* Merge refs/heads/master into update-genesis-time
2020-04-28 20:55:49 +00:00
Raul Jordan
5ed72d4ef9 Add Debug RPC Service to Prysm (#5666)
* adding in proto debug service

* builds

* debug proto

* gaz ignore

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-28 15:43:50 -05:00
Raul Jordan
d0e30ceab2 Remove Old Generated Go Protos (#5667)
* remove old proto generated files
* Merge refs/heads/master into remove-old-protos
2020-04-28 19:47:33 +00:00
Preston Van Loon
9e79809586 Update protobuf, skylib, rules_go, grpc-gateway dependencies (#5657)
* Update dependencies
* Merge branch 'master' into update-deps
* Merge refs/heads/master into update-deps
* Update WORKSPACE
2020-04-28 19:27:56 +00:00
Jim McDonald
9d173dcad2 Update remote signer for 0.11 (#5602)
* Update remote signer for 0.11

* use signing function for aggregate and proof signature

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2020-04-28 09:27:04 -05:00
Preston Van Loon
e30349d410 Add static analysis to enforce usage of InitWithReset (#5654)
* Refactor attestation packing slightly to reduce the skip slot / HTR of process slots
* Merge branch 'master' into refactor-attestation-packing
* gofmt
* Merge branch 'refactor-attestation-packing' of github.com:prysmaticlabs/prysm into refactor-attestation-packing
* Merge branch 'master' of github.com:prysmaticlabs/prysm into refactor-attestation-packing
* Add static analysis to enforce usage of InitWithReset
* Add comment / lint
* fix a few usages
* more fixes for featureconfig.Init
* Fix analyzer
* Merge branch 'sa-fc-init' of github.com:prysmaticlabs/prysm into sa-fc-init
* Merge refs/heads/master into sa-fc-init
* Merge refs/heads/master into sa-fc-init
2020-04-28 01:13:33 +00:00
Ivan Martinez
6700383863 Terminate bootnode after E2E test completion (#5656)
* Terminate bootnode after test completion
2020-04-28 00:49:26 +00:00
Victor Farazdagi
f84e5ad6ef Fix logged errs (#5645)
* fuzz tests, validators stream, and attestation fixed
* hastst
* signinig root fuzz test
* Merge refs/heads/master into fix-logged-errs
* Merge branch 'master' into fix-logged-errs
* Merge branch 'fix-logged-errs' of github.com:prysmaticlabs/prysm into fix-logged-errs
* add head fetchers to inforstream tests
2020-04-28 00:22:37 +00:00
Victor Farazdagi
44b93d9df9 Fix tests depending on configuration flag (#5650)
* fixes segfault
* Merge branch 'master' into fix-nil-segfaults
* upd state
* Merge branch 'master' into fix-nil-segfaults
* updates shard=1
* Merge refs/heads/master into fix-nil-segfaults
* Merge refs/heads/master into fix-nil-segfaults
* Merge refs/heads/master into fix-nil-segfaults
* fixes tests
* Merge branch 'fix-nil-segfaults' of github.com:prysmaticlabs/prysm into fix-nil-segfaults
* reset config to nil
* add flag assertion to other beacon-chain/rpc files
* Merge refs/heads/master into fix-nil-segfaults
* fix the rest featureconfig.init calls
* Merge branch 'fix-nil-segfaults' of github.com:prysmaticlabs/prysm into fix-nil-segfaults
* remove config setting from init
* gazelle
* reset shard back to 4
2020-04-27 19:44:35 +00:00
Ivan Martinez
8327c9d371 Add test for GetValidatorPerformance (#5652)
* Add test for GetValidatorPerformance

* Fix unneeded changes

* Gaz

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-27 13:52:12 -05:00
Nishant Das
e9191e7d6c Create Pcli (#5644)
* add new utility
* Merge branch 'master' into pCli
* Update tools/pcli/main.go

Co-Authored-By: Victor Farazdagi <simple.square@gmail.com>
* Update tools/pcli/main.go

Co-Authored-By: Victor Farazdagi <simple.square@gmail.com>
* Merge refs/heads/master into pCli
* readme and docker fix
* readme
* Merge refs/heads/master into pCli
* Merge refs/heads/master into pCli
* Merge refs/heads/master into pCli
* pending feedback
* builds
* Merge refs/heads/master into pCli
* Merge refs/heads/master into pCli
2020-04-27 16:47:28 +00:00
Raw Pong Ghmoa
f19aa93de2 validator/accounts: don't ask for keystore path if specified (#5641)
* validator/accounts: don't ask for keystore path of specified
* Merge branch 'master' into master
* Merge branch 'master' into master
* validator/accounts restore new validator account creation
* Merge branch 'master' into master
2020-04-27 16:26:51 +00:00
Ivan Martinez
f70635a992 Add post-genesis deposit testing to long-running E2E (#5449)
* WIP add deposits
* Modify validator component
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into e2e-add-depsoits
* Fix e2e
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into e2e-add-depsoits
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into e2e-add-depsoits
* Start running with extra deposits
* Begin adding evluator for e2e deposit
* Get deposit E2E working
* Add more rigorous testing for deposits
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into e2e-add-depsoits
* Improve policy for deposits
* Fix build
* Remove sync testing for long running e2e
* Undo shard change
* Undo unneeded changes
* Adjust for comments
* Merge branch 'master' into e2e-add-depsoits
* Fix bug where long running E2E would always run
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into e2e-add-depsoits
* Merge branch 'e2e-add-depsoits' of https://github.com/0xKiwi/Prysm into e2e-add-depsoits
* Merge branch 'master' into e2e-add-depsoits
2020-04-27 15:59:42 +00:00
Nishant Das
b6353da793 Add Block Batch Limit Flag (#5646)
* add flag

* add flag

* gaz

* fix lint

* fix build issues

* revert initial sync changes

* fix tests

* Update beacon-chain/sync/service.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-27 09:35:40 -05:00
Shay Zluf
4da7701249 Add slasher config file flag (#5639)
* Add slasher config file

* shorter line

* fix package dependencies

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-27 17:14:26 +03:00
terence tsao
e3e9863d92 Add back archival endpoint GetValidatorBalances with fallback (#5620) 2020-04-27 06:44:27 -07:00
Nisen
7d7480527e Missing defer before unlock (#5643)
* missing defer before unlock
2020-04-27 11:20:09 +00:00
Ivan Martinez
eb5513f8c2 Add GenesisValidatorsRoot to GetGenesis (#5619)
* Add GenesisValidatorsRoot to GetGenesis

* Add genesis state

* Add to test

* Change to get val root from genesis fetcher

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-27 09:31:50 +03:00
Nishant Das
07e8609b69 Exit Early from Responding (#5637)
* exit early
2020-04-27 03:18:02 +00:00
wgknowles
08a9fe98fc added prysm.bat for native windows support (#5624) (#5626)
* added first cut of prysm.bat (no SHA/gpg file checking yet)

* updated git commit user.email

* Revert "updated git commit user.email"

This reverts commit a067dc8181.

* Added SHA265 Check, autorestart, ANSI Colors

* Check if valid process, Prefixed PRYSM_autorestart

* Correct echo for downloading beacon-chain

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* fixed ANSI escapes

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
2020-04-26 16:04:02 -07:00
Victor Farazdagi
3782e70e6f checks prysm.sh args size (#5634)
* checks boundaries
* Merge branch 'master' into fix-prysm-sh-unbounded-bug
2020-04-26 21:24:32 +00:00
Preston Van Loon
258d0412c1 GetBlock: Refactor attestation packing (#5632)
* Refactor attestation packing slightly to reduce the skip slot / HTR of process slots
* Merge branch 'master' into refactor-attestation-packing
* gofmt
* Merge branch 'refactor-attestation-packing' of github.com:prysmaticlabs/prysm into refactor-attestation-packing
2020-04-26 21:10:24 +00:00
Victor Farazdagi
d0f3bea8d2 prysm.sh download only option (#5628)
* format srcipt
* download only option
2020-04-26 18:25:48 +00:00
Victor Farazdagi
0806807d61 fixes bug with binary verification (#5627)
* fixes bug with binary verification
* Merge branch 'master' into fix-prysm-sh-verification-bug
* better err message
* Merge branch 'fix-prysm-sh-verification-bug' of github.com:prysmaticlabs/prysm into fix-prysm-sh-verification-bug
2020-04-26 14:09:09 +00:00
Nishant Das
aca9691a0d Stagger Block By Range Responses (#5618)
* refactor method

* fix method

* comments

* Update beacon-chain/sync/rpc_beacon_blocks_by_range.go

Co-Authored-By: terence tsao <terence@prysmaticlabs.com>

* Update beacon-chain/sync/rpc_beacon_blocks_by_range.go

Co-Authored-By: terence tsao <terence@prysmaticlabs.com>

* terence's review

* Apply suggestions from code review

Co-Authored-By: Victor Farazdagi <simple.square@gmail.com>

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-26 13:49:47 +08:00
Preston Van Loon
faa5b309a2 Update prysm.sh to fail fast on armv7l (#5621)
* Update prysm.sh
* Merge branch 'master' into prestonvanloon-patch-1
2020-04-25 20:44:17 +00:00
Preston Van Loon
8a9c9607a5 Update EthereumAPIs to prysmaticlabs/ethereumapis#137 (#5622)
* Update EthereumAPIs to https://github.com/prysmaticlabs/ethereumapis/pull/137 and implement validator index return field
2020-04-25 20:23:36 +00:00
terence tsao
5fbf38c98f Increase regen historical state cache size (#5613)
* Increase cache size and garbage collect

* Update beacon-chain/db/kv/regen_historical_states.go

* Use const
2020-04-25 07:59:29 -07:00
terence tsao
07f6894db1 Use signature for SignedAggregateAttestationAndProof (#5605)
* Use right signature

* Minor refactor and a regression test

* Use proper DomainRequest for mock

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-24 13:12:47 -05:00
terence tsao
3ac15e36a1 Use correct domain to verify aggregate selection (#5604)
* Use domain selection proof
* Merge refs/heads/master into selection-domain
* Merge branch 'master' of github.com:prysmaticlabs/prysm into selection-domain
* Fixed all the tests
* Merge branch 'selection-domain' of github.com:prysmaticlabs/prysm into selection-domain
2020-04-24 17:26:10 +00:00
Preston Van Loon
ffdf248738 Added new PR template (#5598)
* Copied PR template from https://github.com/bazelbuild/rules_go/pull/2425
* Merge branch 'master' into new-pr-template
* Merge refs/heads/master into new-pr-template
* Merge refs/heads/master into new-pr-template
* Merge refs/heads/master into new-pr-template
* Merge refs/heads/master into new-pr-template
2020-04-24 07:29:51 +00:00
Ivan Martinez
cf98de86f4 Fix percentages for validator metric logging (#5609)
* Actually fix percentages
* Merge branch 'master' into fix-percentages
* Merge branch 'master' into fix-percentages
2020-04-24 05:10:09 +00:00
Nishant Das
f9eb54661a Less Noisy P2P Logs (#5607)
* fix logging issues
* change again
* fix errors
* Merge refs/heads/master into lessNoisy
* gaz
* Merge branch 'lessNoisy' of https://github.com/prysmaticlabs/geth-sharding into lessNoisy
2020-04-24 04:10:53 +00:00
Ivan Martinez
921263848a Fix activationEpoch=FarFutureEpoch in validator client logging (#5608)
* Handle pending case where activation epoch is FarFuture

* Fix logs for validators pending activation

* Reword pending activation log
2020-04-23 21:57:36 -04:00
Victor Farazdagi
a33bd94ffb feature default validator keystore path (#5592)
* feature default validator path
* Merge refs/heads/master into fix-validation-path-issue
* Merge refs/heads/master into fix-validation-path-issue
* Merge refs/heads/master into fix-validation-path-issue
* Merge refs/heads/master into fix-validation-path-issue
* Merge refs/heads/master into fix-validation-path-issue
* Merge refs/heads/master into fix-validation-path-issue
2020-04-23 20:02:15 +00:00
Nishant Das
2ebd684924 Add Goodbye Message When Disconnecting With Peers (#5589)
* add goodbye message
* Merge branch 'master' into addGoodbye
* fix interface
* Merge refs/heads/master into addGoodbye
* use wrapper func
* Merge branch 'addGoodbye' of https://github.com/prysmaticlabs/geth-sharding into addGoodbye
* Merge refs/heads/master into addGoodbye
* Merge refs/heads/master into addGoodbye
* Merge refs/heads/master into addGoodbye
* Merge refs/heads/master into addGoodbye
2020-04-23 19:46:24 +00:00
Shay Zluf
37b68ba983 Slasher min span remove lookback (#5591)
* batch db write and read
* fix nil handling
* Merge branch 'master' into batch_min_max_span
* remove commented code
* Merge branch 'master' into batch_min_max_span
* raul feedback
* Merge branch 'batch_min_max_span' of github.com:prysmaticlabs/prysm into batch_min_max_span
* Merge branch 'master' into batch_min_max_span
2020-04-23 19:27:06 +00:00
terence tsao
a78035d6ed Fix getAttPreState memory usage for new-state-mgmt (#5584)
* Starting

* Revert "update commit hash (#5554)"

This reverts commit c69f561fb9.

* Various memory fixes

* Revert "Revert "update commit hash (#5554)""

This reverts commit c9a174bfa7.

* Better error message

* Provide getters

* Using it in DomainData

* Fixed test

* Tests

* Comment

* Update cache for regular mode

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-23 14:03:51 -05:00
Preston Van Loon
a3eeced194 Add a 2 second timeout to fetching eth1data (#5583)
* Add a 2 second timeout to fetching eth1data
* goimports
* fix
* use package const
* Merge refs/heads/master into graceful-failure-eth1data
* fix test
* Merge refs/heads/master into graceful-failure-eth1data
* Merge refs/heads/master into graceful-failure-eth1data
* Merge refs/heads/master into graceful-failure-eth1data
* Merge refs/heads/master into graceful-failure-eth1data
2020-04-23 15:54:51 +00:00
Victor Farazdagi
d1b0348cdb fixes param concatenation (#5594)
* fixes param concatenation
* Merge branch 'master' into prysm-sh-weird-output
2020-04-23 15:24:45 +00:00
Preston Van Loon
a6a2ad4409 Update prysm.sh to include slasher and sig verify (#5543)
* Add gpg detached signature checks

* Add slasher

* Pull key

* move recv after log

* use shasum, download pgp keys

* only download key if not present

* revert bazelversion change

* Actually fail and allow bypass

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-23 09:57:21 -05:00
Shawki Sukkar
49ca0751b6 GetValidatorPerformance only return its status info if the validator is active (#5568)
* Task #1
* First commit
* Fix
* Clean
* Clean
* Clean
* Merge branch 'master' into only-active-validators-log
* Fix
* Clean
* Fix
* Fix
* Fix
* Fix
* Merge branch 'master' into only-active-validators-log
2020-04-23 06:11:13 +00:00
terence tsao
2f2124973b Add HeadGenesisValidatorRoot for DomainData (#5582)
* Provide getters

* Using it in DomainData

* Fixed test

* Tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-22 22:18:29 -05:00
Ivan Martinez
8b058b51d4 Solve -1 ActivationEpoch in validator logging (#5569)
* Fix wrong activation epoch

* Fix bug with activationEpoch

* Add back default of FarFutureEpoch

* Fix tests

* Fix test

* Fix test again

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-22 17:46:57 -05:00
Shay Zluf
9c012cc0c8 Deprecate span map cache flag (#5551)
* deprecate span map cache flag
* fix tests
* nishant feedback
* fix startup
* gaz
* nishant feedback
* gaz
* Merge branch 'master' into deprecate_span_cache
* fix img
* Update slasher/usage_test.go
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* Merge refs/heads/master into deprecate_span_cache
* fix up tests
2020-04-22 15:53:09 +00:00
Victor Farazdagi
9e6b6bc009 fixes issue with ipc path checking (#5577)
* fixes issue with ipc path checking
2020-04-22 11:42:12 +00:00
Jim McDonald
db6dbdcde4 More concise duty logging (#5397)
* More concise duty logging
* Merge branch 'master' into concise-duties
* Remove comment
* Merge branch 'concise-duties' of github.com:mcdee/prysm into concise-duties
* Merge branch 'master' into concise-duties
* Merge branch 'master' into concise-duties
* Merge branch 'master' into concise-duties
* Merge branch 'master' into concise-duties
* Use helpers to calculate slot offset; clarify comment
* Merge branch 'master' into concise-duties
* Merge branch 'master' into concise-duties
* Merge branch 'master' into concise-duties
* Merge branch 'master' into concise-duties
* Merge branch 'master' into concise-duties
2020-04-22 07:50:35 +00:00
Nishant Das
482a054ee1 Handle Nil State Object (#5575)
* handle panic
* Merge branch 'master' into handlePanic
* Merge refs/heads/master into handlePanic
* Merge refs/heads/master into handlePanic
2020-04-22 04:44:33 +00:00
Ivan Martinez
1480d2bfa8 Add hotfix for E2E (#5573)
* Hotfix for e2e
* Add TODO
* Merge branch 'master' into hotfix-e2e
* Merge branch 'master' into hotfix-e2e
2020-04-22 04:23:50 +00:00
Raul Jordan
793c3d27f2 No More EthereumAPIs Patch (#5570)
* no more patch
* Merge refs/heads/master into no-more-patch
* fix build
* Merge refs/heads/master into no-more-patch
* Merge refs/heads/master into no-more-patch
2020-04-22 03:56:06 +00:00
Nishant Das
f880fb4ee4 Shift To Trace Logs (#5561)
* shift to trace
* Merge branch 'master' into shiftTrace
* Merge refs/heads/master into shiftTrace
* Merge refs/heads/master into shiftTrace
* Merge refs/heads/master into shiftTrace
* Merge refs/heads/master into shiftTrace
* Merge refs/heads/master into shiftTrace
* Merge refs/heads/master into shiftTrace
* fix test
* Merge branch 'shiftTrace' of https://github.com/prysmaticlabs/geth-sharding into shiftTrace
2020-04-22 01:21:12 +00:00
terence tsao
7b38e97e83 Invert --disable-new-state-mgmt to --enable-new-state-mgmt (#5567)
* Invert the flag
* Merge branch 'master' into invert-disable-new-state-mgmt
* Merge refs/heads/master into invert-disable-new-state-mgmt
* Add new-state-mgmt to e2e flag
* Merge branch 'invert-disable-new-state-mgmt' of github.com:prysmaticlabs/prysm into invert-disable-new-state-mgmt
* Merge refs/heads/master into invert-disable-new-state-mgmt
2020-04-21 22:30:22 +00:00
Victor Farazdagi
e753cbb04b /healthz endpoint accepts JSON now (#5558)
* /healthz endpoint accepts JSON now
* Merge refs/heads/master into json-healthz
* Merge refs/heads/master into json-healthz
* Merge refs/heads/master into json-healthz
* Merge refs/heads/master into json-healthz
* Merge refs/heads/master into json-healthz
* Merge refs/heads/master into json-healthz
2020-04-21 20:58:53 +00:00
Ivan Martinez
c2daf8d82e Change Validator Status for visible deposit back to DEPOSITED (#5563)
* Change valstatus for visible deposit back to DEPOSITED
* Rename logs
* Merge branch 'master' into val-status
* Fix tests
* Merge branch 'val-status' of https://github.com/prysmaticlabs/prysm into val-status
* Fix tests
* Change test
* Merge branch 'master' into val-status
* Text changes
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into val-status
* Merge branch 'val-status' of https://github.com/prysmaticlabs/prysm into val-status
* Update validator/client/validator.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Update validator/client/validator.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge branch 'val-status' of https://github.com/prysmaticlabs/prysm into val-status
* Merge branch 'master' into val-status
2020-04-21 19:11:27 +00:00
terence tsao
480ddb7c3d Continue if archival state is not in DB (#5565)
* Continue if archival state is not availble to generate
* Fixed test
* Merge branch 'master' into save-blocks-splitslot
* Merge refs/heads/master into save-blocks-splitslot
2020-04-21 18:18:55 +00:00
Victor Farazdagi
0f08bd288c fix tests in //beacon-chain/rpc/beacon (#5559)
* assert new state is not disabled
* Merge refs/heads/master into fix-list-indexed-atts-test
* add helper method
* Merge branch 'fix-list-indexed-atts-test' of github.com:prysmaticlabs/prysm into fix-list-indexed-atts-test
* xx
* xx
* Merge refs/heads/master into fix-list-indexed-atts-test
2020-04-21 17:44:18 +00:00
Shay Zluf
8cba109350 Slasher batch db read and a write (#5534)
* batch db read

* fix test

* debug

* write function and test

* test rename

* add to interface

* change order

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-21 11:50:04 -05:00
terence tsao
199c50be47 Migration should not fail process block routine (#5557)
* Continue rather than fail
* Merge branch 'master' into migrate-should-not-fail-block
* Merge refs/heads/master into migrate-should-not-fail-block
2020-04-21 14:44:43 +00:00
Nishant Das
c69f561fb9 update commit hash (#5554) 2020-04-21 09:07:06 -05:00
Ivan Martinez
19b879ec17 Change ListIndexedAttestations to convert attestations from target root (#5548) 2020-04-20 22:48:31 -04:00
terence tsao
54faf8564f Add back archival endpoint GetValidatorActiveSetChanges with fallback (#5519)
* Modify `GetValidatorActiveSetChanges` to use new state service  (#5408)

* Fix import and not use
* Update workspace for new spec test
* Fix workspace
* Merge refs/heads/master into v0.10.1
* Update workspace with new ethapi commit
* Unblock a few tests
* Merge refs/heads/master into v0.10.1
* fixed block op test
* gaz
* Merge refs/heads/master into v0.10.1
* Skip gen state test (test setup issue
* Updated hysteresis config
* Updated epoch processing for new hyteresis
* Updated tests
* regen proto beacon
* update state util for state root
* update state types
* update getter and setters
* update compute domain and get domain and tests
* update validators
* Add forkdata proto
* Updated compute domain api, moved it to helper pkg
* Merge refs/heads/master into v0.10.1
* Fixed all core tests
* Fixed all the sync tests
* Fixed all the rpc tests
* Merge refs/heads/master into v0.10.1
* Merge refs/heads/master into v0.10.1
* Fixed conflict
* Fixed conflict
* Conflict fix
* visibility
* Fixed validator tests
* Fixing test util
* Fixed rest of non spec tests
* Fixed a bug proposer index wasn't included
* gaz
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Updated eth1 data voting period to epoch based
* Fixed failed tests
* fix bug
* fix error
* Fixed more misc tests
* Add new SignedAggregateAndProof to pass spec test
* Update minimalConfig.PersistentCommitteePeriod
* allow to rebuild trie
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Skip e2e tests
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Align aggregator action with v0.11 (#5146)
* Remove Head Root from Beacon Block by Range Request (#5165)

* make proto changes
* remove head root
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into v0.11
* add back herumi's library
* Update ethapi in workspace, started fixing test. Hand off to Nishant
* fix build
* All tests passing
* Align finalized slot check with v0.11 (#5166)
* Merge branch 'master' into v0.11
* Add DoS resistance for v0.11 (#5158)
* Add Fork Digest Helper (#5173)
* Extend DoS prevention to rest of operation objects (#5174)

* Update mapping

* Add caches

* Update seen block in validation pipeline

* Update seen att in validation pipeline

* Update seen att in validation pipeline

* Fixed rest of tests

* Gazelle

* Better writes

* Lint

* Preston's feedback

* Switched to LRU cache and fixed tests

* Gazelle

* Fix test

* Update proposer slashing

* Update proposer slashing

* Fixed a block test

* Update exit

* Update atteser slashing

* Raul's feedback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Add remote keymanager (#5133)

* Add remote keymanager

* Add generic signRoot() helper

* Add tests for remote keymanager

* NewRemote -> NewRemoteWallet

* signRoot -> signOject, to increase reuse

* Fix end-to-end compile error

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Add Snappy Framing to the Encoder (#5172)

* change to framing

* more fixes

* fix everything

* add stricter limits

* preston feedback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: rauljordan <raul@prysmaticlabs.com>
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Move Subnet Functionality to its Own File (#5179)

* move subnets to their own file

* fix build fail

* build

* Update beacon-chain/p2p/discovery_test.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Sync with master
* Verify proposer signature in sync (#5206)
* Fix Signed Attestation In Sync (#5207)
* Add Eth2 Fork ENR Functionality (#5181)

* add fork entry enr

* add in fork

* add the required fork entry to node

* add and retrieve fork entry

* await state initialized

* utilize new structure

* more progress, utilizing a config map instead

* send the genesis validators root via the event feed

* struct method for discovery

* fix broken builds

* fixed up more tsts using state feed initializer

* fix up most tests

* only one more failing test

* almost done with tests

* p2p tests all pass

* config fix

* fix blockchain test

* gaz

* add in todo

* lint

* add compare func

* ensure fork ENR versions match between peers

* add in test for discovery

* test name

* tests complete

* tests done

* done

* comments

* fix all flakes

* addressed comments

* build using ssz gen

* marshal record

* use custom ssz

* deduplicate import

* fix build

* add enr proto

* p2p tests done

Co-authored-by: nisdas <nishdas93@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Verify aggregator signature in sync (#5208)
* Add Fork Digest For Gossip Topics (#5191)

* update for the day

* fix remaining failing test

* fix one more test

* change message

* Apply suggestions from code review

Co-Authored-By: terence tsao <terence@prysmaticlabs.com>

* terence's review

* implement fork digest'

* align digest to interface'

* passed all tests

* spawn in goroutine

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
* Fix Incorrect Attester Slashing Method (#5229)
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Remove keystore keymanager from validator (#5236)

* Remove keystore keymanager from validator

* Update dependency

* Update validator/flags/flags.go

* Update validator/flags/flags.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
* fix broadcaster
* update metrics with fork digest for p2p (#5251)

* update metrics with fork digest for p2p

* update p2p metrics

* update metrics using att values

* wrapped up

* fix bug

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Fix incorrect domain type comments (#5250)

* Fix incorrect domain type comments
* resolve conflicts
* fix broken broadcast test
* fix tests
* include protocol suffix
* fix confs
* lint
* fix test
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Merge branch 'master' of github.com:prysmaticlabs/prysm into v0.11
* resolve broken slasher test'
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Merge branch 'master' into v0.11
* fix config override
* Remove deprecated parameters (#5249)
* Avoid div by zero in extreme balance case (#5273)

* Return effective balance increment instead of 1

* Update to new spec tests v0.11.1

* Revert "Regen historical states for `new-state-mgmt` compatibility (#5261)"

This reverts commit df9a534826.

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Revert "Remove deprecated parameters (#5249)" (#5276)

This reverts commit 7d17c9ac34.
* Verify block proposer index before gossip  (#5274)

* Update pipeline

* Update tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Add in Proposer Index to Custom HTR (#5269)

* fix test

* Update beacon-chain/state/stateutil/blocks_test.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Resolve Flakey P2P Tests (#5285)

* double time for flakey test

* fix test flakeyness in p2p:

* flakey

* time tolerance

* greater tolerance
* Merge branch 'master' into v0.11
* release resources correctly (#5287)
* Merge refs/heads/master into v0.11
* Enable NOISE Handshake by Default v0.11 (#5272)

* noise handshakes by default

* fix build

* noisy noise everywhere

* deprecated noisy noise flag with more noise

* add secio as fallback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: nisdas <nishdas93@gmail.com>
* Merge refs/heads/master into v0.11
* new ports
* fix broken build
* Make `new-state-mgmt` canonical  (#5289)

* Invert the flags
* Update checking messages
* Fixed all db tests
* Fixed rest of the block chain tests
* Fix chain race tests
* Fixed rpc tests
* Disable soudns better...
* Merge branch 'v0.11' into invert-new-state-mgmt
* Merge refs/heads/v0.11 into invert-new-state-mgmt
* Fix export
* Merge branch 'invert-new-state-mgmt' of github.com:prysmaticlabs/prysm into invert-new-state-mgmt
* Fix conflict tests
* Gazelle
* Merge refs/heads/v0.11 into invert-new-state-mgmt
* Merge refs/heads/v0.11 into invert-new-state-mgmt
* Merge branch 'master' into v0.11
* resolve flakeyness
* Merge refs/heads/master into v0.11
* Merge refs/heads/master into v0.11
* Detect Proposer Slashing Implementation (#5139)

* detect blocks

* detect blocks

* use stub

* use stub

* use stub

* todo

* fix test

* add tests and utils

* fix imports

* fix imports

* fix comment

* todo

* proposerIndex

* fix broken test

* formatting and simplified if

* Update slasher/detection/service.go

* Update slasher/detection/testing/utils.go

Co-Authored-By: terence tsao <terence@prysmaticlabs.com>

* fixed up final comments

* better naming

* Update slasher/detection/service.go

* Update slasher/detection/service.go

* Update slasher/detection/service.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>

* no more named args

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into v0.11
* Add Metadata And Ping RPC methods (#5271)

* add new proto files

* add flag and helper

* add initializer

* imports

* add ping method

* add receive/send ping request

* add ping test

* refactor rpc methods and add ping test

* finish adding all tests

* fix up tests

* Apply suggestions from code review

* lint

* imports

* lint

* Update beacon-chain/p2p/service.go

* Update shared/cmd/flags.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into v0.11
* Updates for remote keymanager (#5260)
* Merge branch 'spec-v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Merge remote-tracking branch 'origin' into v0.11
* Update to slash by slot instead of epoch (#5297)

* change to slash by slot instead of epoch

* gaz

* fix test

* fix test

* fix infinite loop on error parse
* Sync with master
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Update proposer protection to v0.11 (#5292)

* Complete most of changes

* Fix other tests

* Test progress

* Tests

* Finish tests

* update pbs

* Fix mocked tests

* Gazelle

* pt 2

* Fix

* Fixes

* Fix tests wit hwrong copying
* Merge refs/heads/master into v0.11
* Merge refs/heads/master into v0.11
* Implement `SubscribeCommitteeSubnet` method (#5299)

* Add client implementation

* Update workspace

* Update server

* Update service

* Gaz

* Mocks

* Fixed validator tests

* Add round tirp tests

* Fixed subnet test

* Comment

* Update committee cache

* Comment

* Update RPC

* Fixed test

* Nishant's comment

* Gaz

* Refresh ENR is for epoch

* Needs to be append
* Merge refs/heads/master into v0.11
* resolve confs
* Validator subscribe subnet to next epoch (#5312)

* Alert to subscribe to next epoch

* Fixed tests

* Comments

* Fixed tests

* Update validator/client/validator.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Revert "Revert "Remove deprecated parameters (#5249)" (#5276)" (#5277)

This reverts commit 47e5a2cf96.
* Aggregate on demand for v0.11 (#5302)

* Add client implementation

* Update workspace

* Update server

* Update service

* Gaz

* Mocks

* Fixed validator tests

* Add round tirp tests

* Fixed subnet test

* Wait 1/3 on validator side

* Lint

* Comment

* Update committee cache

* Comment

* Update RPC

* Fixed test

* Nishant's comment

* Gaz

* Refresh ENR is for epoch

* Needs to be append

* Fixed duplication

* Tests

* Skip e2e

* Update beacon-chain/rpc/validator/aggregator.go

Co-Authored-By: shayzluf <thezluf@gmail.com>

* Apply suggestions from code review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: shayzluf <thezluf@gmail.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
* Refactor Dynamic Subscriptions (#5318)

* clean up

* comment

* metrics

* fix

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/master into v0.11
* Fix listindexed attestations and detect historic attestations (#5321)

* fix list indexed attestations

* fix tests

* goimports

* names
* Add check for slot == 0 (#5322)
* Change attester protection to return default if DB is empty (#5323)

* Change how default values are set

* Remove unused imports

* Remove wasteful db call

* Fix db tests

* Fix db test
* Merge refs/heads/master into v0.11
* fix it (#5326)
* V0.11 run time fixes to use interop config (#5324)

* Started testing
* Bunch of fixes
* use-interop
* Sync with v0.11
* Conflict
* Uncomment wait for activation
* Move pending block queue from subscriber to validator pipeline
* Merge branch 'v0.11' into use-interop-config
* passing tests
* Merge refs/heads/v0.11 into use-interop-config
* Merge refs/heads/v0.11 into use-interop-config
* Merge refs/heads/master into v0.11
* Merge refs/heads/master into v0.11
* Merge refs/heads/master into v0.11
* Nil Checks in Process Attestation v0.11 (#5331)

* Started testing

* Bunch of fixes

* use-interop

* Sync with v0.11

* Uncomment wait for activation

* Move pending block queue from subscriber to validator pipeline

* passing tests

* nil checks to prevent panics

* lint

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Validator batch subscribe subnets (#5332)

* Update both beacon node and validator

* Comments

* Tests

* Lint

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Validator smarter subscribe (#5334)
* Fix incorrect proposer index calculation (#5336)

* Use correct parent state

* Fixed test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* enhance error
* enhance error
* Update P2P Service to Handle Local Metadata (#5319)

* add metadata to ENR

* add new methods

* glue everything

* fix all tests and refs

* add tests

* add more tests

* Apply suggestions from code review

* fix method

* raul's review

* gaz

* fix test setup

* fix all tests

* better naming

* fix broken test

* validate nil

Co-authored-by: rauljordan <raul@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Revert "Revert "Revert "Remove deprecated parameters (#5249)" (#5276)" (#5277)" (#5343)

This reverts commit e5aef1686e.
* Wait for Genesis Event to Start P2P (#5303)

* use event feed for state initialized events

* add in handler for tests

* wait till genesis for p2p

* Apply suggestions from code review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/master into v0.11
* Avoid duplicated aggregation request (#5346)

* Avoid duplicated aggregation request

* Test and lock

* Gaz
* Fix Validate For Metadata (#5348)

* return true

* shay's review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Multiple Proposer Slots Allowed Per Epoch for Validators (#5344)

* allow multiple proposer slots

* multi propose

* proposer indices to slots map

* remove deprecated comm assign

* Apply suggestions from code review

* resolve broken tests, add logic in validator client

* fix val tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Networking Fixes (#5349)

* close stream later

* add ping method

* add method

* lint
* More efficient aggregation on demand (#5354)
* Return Nil Error if Pre-Genesis in P2P Service Healthz Check (#5355)

* pregenesis healthz check:

* optimal

* right order

* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* no comment

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Release DiscoveryV5 for Testnet Restart (#5357)

* release discv5

* fix build
* Fix Overflow in Status Check (#5361)

* fix overflow

* Apply suggestions from code review
* Merge branch 'master' of github.com:prysmaticlabs/prysm into v0.11
* fix after merge
* Merge refs/heads/master into v0.11
* Make Mainnet Config Default, No More Demo Config  (#5367)

* bye bye demo config

* gaz

* fix usage

* fix dep

* gaz

* Update default balance for sendDeposits

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Use FastSSZ Marshal/Unmarshal for DB Encodings in v0.11.1 (#5351)

* try

* use marshaler structure for db instead of proto

* white list types

* attempt

* revert

* testutil.NewBeaconState()

* Fully populate fields for round trip ssz marshal

* fix //beacon-chain/db/kv:go_default_test

* more passing tests

* another test target passed

* fixed stategen

* blockchain tests green

* passing sync

* more targets fixed

* more test fixes in rpc/validator

* most rpc val

* validators test fixes

* skip round robin old

* aggregate test

* whitelist done

* Update beacon-chain/rpc/validator/attester_test.go

* edit baz

* Fixed tests

* Fixed getblock test

* Add back init

* reduce test size

* fix broken build

* tests pass

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Reconnect slasher streams on beacon node shutdown (#5376)

* restart streams on beacon node shutdown

* fix comment

* remove export

* ivan feedback

* ivan feedback

* case insensitive

* Update slasher/beaconclient/receivers.go

* raul feedback

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge branch 'master' into v0.11
* Merge refs/heads/master into v0.11
* Amend Faucet to Offer 32.5 ETH for v0.11 (#5378)

* deposit amount in faucet

* fix eth amount

* gas cost
* unskip exec transition test
* Revert "Enable NOISE Handshake by Default v0.11 (#5272)" (#5381)

This reverts commit a8d32d504a.
* Merge refs/heads/master into v0.11
* use string for deposit flag
* Update Bootnode to v0.11 (#5387)

* fix bootnode

* add changes

* gaz

* fix docker
* Merge branch 'master' of github.com:prysmaticlabs/prysm into v0.11
* build fix
* fix flaky test
* Merge refs/heads/master into v0.11
* Unskip E2E for V0.11 (#5386)

* Begin work on fixing e2e for v0.11

* Start bootnode work

* Begin implementing bootnode into e2e

* Fix E2E for v0.11

* Remove extra

* gaz

* Remove unused key gen code

* Remove trailing multiaddr code

* add skip for slashing

* Fix slashing e2e

* Fix docker image build
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into v0.11
* Merge refs/heads/master into v0.11
* Merge branch 'master' of github.com:prysmaticlabs/prysm into v0.11
* Update beacon-chain/p2p/broadcaster_test.go
* Merge refs/heads/master into v0.11
* Update GetValidatorActiveSetChanges
* Fixed tests
* Pass E2E Tests for v0.11 and Enable Attestation Subnets By Default (#5407)
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update README.md

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Apply suggestions from code review

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update beacon-chain/p2p/config.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update shared/keystore/deposit_input.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update tools/faucet/server.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update proto/beacon/p2p/v1/BUILD.bazel

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update shared/bls/spectest/aggregate_verify_test.go
* Merge refs/heads/v0.11 into fix-active-set-changes
* Addressed feedback. All test passing
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update beacon-chain/core/blocks/block_operations_fuzz_test.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update beacon-chain/core/blocks/block_operations_test.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update shared/testutil/helpers.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update beacon-chain/core/helpers/signing_root.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Resolve Misc v0.11 Items (Raul) (#5414)

* address all comments

* set faucet

* nishant feedback

* Update beacon-chain/p2p/service.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Revert keymanager changes (#5416)

* Revert "Updates for remote keymanager (#5260)"

This reverts commit bbcd895db5.

* Revert "Remove keystore keymanager from validator (#5236)"

This reverts commit 46008770c1.

* Revert "Update eth2 wallet keymanager (#4984)"

This reverts commit 7f7ef43f21.

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update BLS and limit visibility (#5415)

* remove duplicated BLS, add golang.org/x/mod

* Update BLS and restrict visibility

* fix build
* Merge refs/heads/v0.11 into fix-active-set-changes
* Fix eth1data test and fix order of ops (#5413)
* Merge refs/heads/v0.11 into fix-active-set-changes
* use multiaddr builder (#5419)
* Merge refs/heads/v0.11 into fix-active-set-changes
* Unskip benchutil and minor v0.11 fixes (#5417)

* Unskip benchutil tests

* Remove protos and gaz

* Fixes
* Merge refs/heads/v0.11 into fix-active-set-changes
* Networking Fixes (#5421)

* check

* fix test

* fix size

* fix test

* more fixes

* fix test again
* Merge refs/heads/v0.11 into fix-active-set-changes
* Update ethereum APIs with latest master
* Merge refs/heads/v0.11 into fix-active-set-changes
* Error handling for v0.11 tests (#5428)

* Proper err handling for tests

* Lint

* Fixed rest of the tests

* Gaz

* Fixed old master tests
* Sync with master
* Rm old aggregate_test.go
* Sync with v0.11
* Sync with master
* Merge refs/heads/master into fix-active-set-changes
* Merge refs/heads/master into fix-active-set-changes
* Merge refs/heads/master into fix-active-set-changes
* Merge refs/heads/master into fix-active-set-changes
* Merge refs/heads/master into fix-active-set-changes
* Merge branch 'master' into fix-active-set-changes
* Gaz
* Merge refs/heads/master into fix-active-set-changes
* Fixed test
* Merge branch 'fix-active-set-changes' of github.com:prysmaticlabs/prysm into fix-active-set-changes
* Merge refs/heads/master into fix-active-set-changes

* Active set chagne with fallback

* Add back the old tests

* Fixed test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2020-04-20 19:59:34 -05:00
Ivan Martinez
c8fa31ac97 WaitForActivation optimizations (#5396)
* WaitForActrivation improvements
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into waitforactivation
* Changes to handle new statuses
* Merge branch 'master' into waitforactivation
* Fix tests
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into waitforactivation
* Merge branch 'waitforactivation' of https://github.com/0xKiwi/Prysm into waitforactivation
* Remove unkown status being set
* Fix test
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into waitforactivation
* Merge branch 'master' into waitforactivation
* Modify logging slightly
* Merge branch 'waitforactivation' of https://github.com/0xKiwi/Prysm into waitforactivation
* Improve deposit ux
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into waitforactivation
* Add test for logs
* Rename
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into waitforactivation
* Merge branch 'master' into waitforactivation
* Merge branch 'master' into waitforactivation
* Merge branch 'master' into waitforactivation
* Merge branch 'master' into waitforactivation
* Merge branch 'master' into waitforactivation
* Merge branch 'master' into waitforactivation
* Merge branch 'master' into waitforactivation
2020-04-20 23:52:39 +00:00
Ivan Martinez
25102e0978 Use WaitForSynced in validator client for startup (#5465)
* Add WaitForSynced to beacon-chain
* Fix build issues
* Fix comment
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into simplify-validator
* Fix tests
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into simplify-validator
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into simplify-validator
* Change validator client to use WaitForSynced
* Change prysm script to support windows
* Update prysm.sh
* Merge branch '0xKiwi-patch-1' of https://github.com/prysmaticlabs/prysm into simplify-val-client
* Merge branch 'master' into simplify-val-client
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into simplify-val-client
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into simplify-val-client
* Add to mock
* Merge branch 'simplify-val-client' of https://github.com/0xKiwi/Prysm into simplify-val-client
* Fix mocks
* Add feature flag for WaitForSynced
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into simplify-val-client
* Fix flag
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into simplify-val-client
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into simplify-val-client
* Remove comment
* Merge branch 'master' into simplify-val-client
* Merge branch 'master' into simplify-val-client
* Merge branch 'master' into simplify-val-client
* Merge branch 'master' into simplify-val-client
2020-04-20 23:16:53 +00:00
Ivan Martinez
60bf3edf0a Optimize GetDuties to not call Eth1 functions (#5516)
* Remove unneeded validator status calls for GetDuties
* Cleanup validator runner function
* Improvements
* Undo validator client changes
* Merge branch 'master' into optimize-getduties
* Revert "Undo validator client changes"

This reverts commit 4385181eaf.
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into optimize-getduties
* Remove unneeded tests
* Merge branch 'optimize-getduties' of https://github.com/0xKiwi/Prysm into optimize-getduties
* Revert "Cleanup validator runner function"

This reverts commit f0c8c5e8bc.
* Add back test
* Optimize getduties
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into optimize-getduties
* Merge branch 'master' into optimize-getduties
2020-04-20 22:24:50 +00:00
terence tsao
982d93547a Log warn instead of return error (#5547)
* Fix 5395
2020-04-20 21:32:56 +00:00
Nishant Das
7b89b17ed2 Update to 1.14.1 (#5535)
* update to 1.14.1
* Merge branch 'master' into updatego1.14.1
* Merge refs/heads/master into updatego1.14.1
* Merge refs/heads/master into updatego1.14.1
* Merge refs/heads/master into updatego1.14.1
* Merge refs/heads/master into updatego1.14.1
2020-04-20 20:49:03 +00:00
terence tsao
2a0711ab01 Regen and save historical states as default (#5544)
* Better error
* Use copy
* Conflict
* Fixed a bug on using pre state. Added a LRU cache for saving pre state.
* Removed interaction menu. Ran Gazelle
* Fixed delete state to continue than exit
* Gazelle
* Merge branch 'master' of github.com:prysmaticlabs/prysm into regen-default
* Merge refs/heads/master into regen-default
* Added a warning message
* Merge branch 'regen-default' of github.com:prysmaticlabs/prysm into regen-default
* Merge refs/heads/master into regen-default
2020-04-20 20:19:53 +00:00
Raul Jordan
9255a2b3c1 Add Clock-Based Slot to Metrics (#5545)
* clock based slot
* Merge refs/heads/master into highest-possible-slot
2020-04-20 19:49:25 +00:00
Raul Jordan
61c96f50a0 Add Metrics to Bootnode (#5460)
* bootnode metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* docker bootnode deps
* Merge branch 'master' into bootnode-metrics
* fix
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* Merge refs/heads/master into bootnode-metrics
* resolve build
2020-04-20 19:02:09 +00:00
Victor Farazdagi
b663086a88 add --dev flag (#5539)
* add --dev flag
* Merge refs/heads/master into dev-flag
* Update shared/featureconfig/config.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Update shared/featureconfig/flags.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/master into dev-flag
2020-04-20 17:27:24 +00:00
Raul Jordan
37cba662f1 Run Gofmt on Repo (#5541)
* toggle flags
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* Merge branch 'master' of github.com:prysmaticlabs/prysm
* run gofmt
* Merge branch 'master' into lint-repo
2020-04-20 16:35:04 +00:00
Shay Zluf
fae307e5a2 Fix slasher historic attestation detection (#5532)
* fix slasher historic attestation detection

* revert log changes
2020-04-20 11:11:53 -05:00
Nishant Das
639e3072fe Cancel Initial Sync Properly (#5529)
* fix cancelling
* Merge branch 'master' into cancelServices
* Merge refs/heads/master into cancelServices
* Merge refs/heads/master into cancelServices
2020-04-20 04:04:45 +00:00
terence tsao
984644257e Add back archival endpoint ListBeaconCommittees with fallback (#5518)
* Add fallback
* Add back the old tests
* Merge refs/heads/master into list-beacon-committee-fallback
* Merge refs/heads/master into list-beacon-committee-fallback
* Merge refs/heads/master into list-beacon-committee-fallback
* Merge refs/heads/master into list-beacon-committee-fallback
* Merge refs/heads/master into list-beacon-committee-fallback
* Merge refs/heads/master into list-beacon-committee-fallback
2020-04-20 03:41:32 +00:00
Preston Van Loon
9ae492e2cd Validator: fix percentages to be per 100 (#5527)
* fix percentages to be per 100
* Merge branch 'master' into fix-percentages
* Merge refs/heads/master into fix-percentages
2020-04-20 03:10:53 +00:00
Preston Van Loon
1c6d1fabf3 Update prysm.sh to use prysmaticlabs.com/releases (#5528)
* Update prysm.sh to use prysmaticlabs.com/releases to avoid github rate limits
2020-04-20 02:56:59 +00:00
Nishant Das
b61d320613 Make Connections Less Aggressive (#5488)
* make less aggressive
* Merge branch 'master' into lessAggressive
* Merge branch 'master' into lessAggressive
* Merge refs/heads/master into lessAggressive
* Merge refs/heads/master into lessAggressive
* Merge refs/heads/master into lessAggressive
2020-04-20 02:11:18 +00:00
terence tsao
62da94bd0b Add back archival endpoint ValidatorParticipation with fallback (#5520)
* Modify `GetValidatorParticipation` to use new state service (#5409)

* Skip 2 more minimal tests

* Update readme

* gaz

* Fix import and not use

* Update workspace for new spec test

* Fix workspace

* Update workspace with new ethapi commit

* Unblock a few tests

* fixed block op test

* gaz

* Skip gen state test (test setup issue

* Updated hysteresis config

* Updated epoch processing for new hyteresis

* Updated tests

* regen proto beacon

* update state util for state root

* update state types

* update getter and setters

* update compute domain and get domain and tests

* update validators

* Add forkdata proto

* Updated compute domain api, moved it to helper pkg

* Fixed all core tests

* Fixed all the sync tests

* Fixed all the rpc tests

* Conflict fix

* visibility

* Fixed validator tests

* Fixing test util

* Fixed rest of non spec tests

* Fixed a bug proposer index wasn't included

* gaz

* Updated eth1 data voting period to epoch based

* Fixed failed tests

* fix bug

* fix error

* Fixed more misc tests

* Add new SignedAggregateAndProof to pass spec test

* Update minimalConfig.PersistentCommitteePeriod

* allow to rebuild trie

* Skip e2e tests

* Align aggregator action with v0.11 (#5146)

* Remove Head Root from Beacon Block by Range Request (#5165)

* make proto changes
* remove head root

* add back herumi's library

* Update ethapi in workspace, started fixing test. Hand off to Nishant

* fix build

* Align finalized slot check with v0.11 (#5166)

* Add DoS resistance for v0.11 (#5158)

* Add Fork Digest Helper (#5173)

* Extend DoS prevention to rest of operation objects (#5174)

* Update mapping

* Add caches

* Update seen block in validation pipeline

* Update seen att in validation pipeline

* Update seen att in validation pipeline

* Fixed rest of tests

* Gazelle

* Better writes

* Lint

* Preston's feedback

* Switched to LRU cache and fixed tests

* Gazelle

* Fix test

* Update proposer slashing

* Update proposer slashing

* Fixed a block test

* Update exit

* Update atteser slashing

* Raul's feedback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Add remote keymanager (#5133)

* Add remote keymanager

* Add generic signRoot() helper

* Add tests for remote keymanager

* NewRemote -> NewRemoteWallet

* signRoot -> signOject, to increase reuse

* Fix end-to-end compile error

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* Add Snappy Framing to the Encoder (#5172)

* change to framing

* more fixes

* fix everything

* add stricter limits

* preston feedback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: rauljordan <raul@prysmaticlabs.com>

* Move Subnet Functionality to its Own File (#5179)

* move subnets to their own file

* fix build fail

* build

* Update beacon-chain/p2p/discovery_test.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Verify proposer signature in sync (#5206)

* Fix Signed Attestation In Sync (#5207)

* Add Eth2 Fork ENR Functionality (#5181)

* add fork entry enr

* add in fork

* add the required fork entry to node

* add and retrieve fork entry

* await state initialized

* utilize new structure

* more progress, utilizing a config map instead

* send the genesis validators root via the event feed

* struct method for discovery

* fix broken builds

* fixed up more tsts using state feed initializer

* fix up most tests

* only one more failing test

* almost done with tests

* p2p tests all pass

* config fix

* fix blockchain test

* gaz

* add in todo

* lint

* add compare func

* ensure fork ENR versions match between peers

* add in test for discovery

* test name

* tests complete

* tests done

* done

* comments

* fix all flakes

* addressed comments

* build using ssz gen

* marshal record

* use custom ssz

* deduplicate import

* fix build

* add enr proto

* p2p tests done

Co-authored-by: nisdas <nishdas93@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Verify aggregator signature in sync (#5208)

* Add Fork Digest For Gossip Topics (#5191)

* update for the day

* fix remaining failing test

* fix one more test

* change message

* Apply suggestions from code review

Co-Authored-By: terence tsao <terence@prysmaticlabs.com>

* terence's review

* implement fork digest'

* align digest to interface'

* passed all tests

* spawn in goroutine

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>

* Fix Incorrect Attester Slashing Method (#5229)

* Remove keystore keymanager from validator (#5236)

* Remove keystore keymanager from validator

* Update dependency

* Update validator/flags/flags.go

* Update validator/flags/flags.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* fix broadcaster

* update metrics with fork digest for p2p (#5251)

* update metrics with fork digest for p2p

* update p2p metrics

* update metrics using att values

* wrapped up

* fix bug

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Fix incorrect domain type comments (#5250)

* Fix incorrect domain type comments

* fix broken broadcast test

* fix tests

* include protocol suffix

* lint

* fix test

* resolve broken slasher test'

* fix config override

* Remove deprecated parameters (#5249)

* Avoid div by zero in extreme balance case (#5273)

* Return effective balance increment instead of 1

* Update to new spec tests v0.11.1

* Revert "Regen historical states for `new-state-mgmt` compatibility (#5261)"

This reverts commit df9a534826.

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Revert "Remove deprecated parameters (#5249)" (#5276)

This reverts commit 7d17c9ac34.

* Verify block proposer index before gossip  (#5274)

* Update pipeline

* Update tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Add in Proposer Index to Custom HTR (#5269)

* fix test

* Update beacon-chain/state/stateutil/blocks_test.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Resolve Flakey P2P Tests (#5285)

* double time for flakey test

* fix test flakeyness in p2p:

* flakey

* time tolerance

* greater tolerance

* release resources correctly (#5287)

* Enable NOISE Handshake by Default v0.11 (#5272)

* noise handshakes by default

* fix build

* noisy noise everywhere

* deprecated noisy noise flag with more noise

* add secio as fallback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: nisdas <nishdas93@gmail.com>

* new ports

* fix broken build

* Make `new-state-mgmt` canonical  (#5289)

* Invert the flags
* Update checking messages
* Fixed all db tests
* Fixed rest of the block chain tests
* Fix chain race tests
* Fixed rpc tests
* Disable soudns better...
* Merge branch 'v0.11' into invert-new-state-mgmt
* Merge refs/heads/v0.11 into invert-new-state-mgmt
* Fix export
* Merge branch 'invert-new-state-mgmt' of github.com:prysmaticlabs/prysm into invert-new-state-mgmt
* Fix conflict tests
* Gazelle
* Merge refs/heads/v0.11 into invert-new-state-mgmt
* Merge refs/heads/v0.11 into invert-new-state-mgmt

* resolve flakeyness

* Detect Proposer Slashing Implementation (#5139)

* detect blocks

* detect blocks

* use stub

* use stub

* use stub

* todo

* fix test

* add tests and utils

* fix imports

* fix imports

* fix comment

* todo

* proposerIndex

* fix broken test

* formatting and simplified if

* Update slasher/detection/service.go

* Update slasher/detection/testing/utils.go

Co-Authored-By: terence tsao <terence@prysmaticlabs.com>

* fixed up final comments

* better naming

* Update slasher/detection/service.go

* Update slasher/detection/service.go

* Update slasher/detection/service.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>

* no more named args

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>

* Add Metadata And Ping RPC methods (#5271)

* add new proto files

* add flag and helper

* add initializer

* imports

* add ping method

* add receive/send ping request

* add ping test

* refactor rpc methods and add ping test

* finish adding all tests

* fix up tests

* Apply suggestions from code review

* lint

* imports

* lint

* Update beacon-chain/p2p/service.go

* Update shared/cmd/flags.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* Updates for remote keymanager (#5260)

* Update to slash by slot instead of epoch (#5297)

* change to slash by slot instead of epoch

* gaz

* fix test

* fix test

* fix infinite loop on error parse

* Update proposer protection to v0.11 (#5292)

* Complete most of changes

* Fix other tests

* Test progress

* Tests

* Finish tests

* update pbs

* Fix mocked tests

* Gazelle

* pt 2

* Fix

* Fixes

* Fix tests wit hwrong copying

* Implement `SubscribeCommitteeSubnet` method (#5299)

* Add client implementation

* Update workspace

* Update server

* Update service

* Gaz

* Mocks

* Fixed validator tests

* Add round tirp tests

* Fixed subnet test

* Comment

* Update committee cache

* Comment

* Update RPC

* Fixed test

* Nishant's comment

* Gaz

* Refresh ENR is for epoch

* Needs to be append

* Validator subscribe subnet to next epoch (#5312)

* Alert to subscribe to next epoch

* Fixed tests

* Comments

* Fixed tests

* Update validator/client/validator.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Revert "Revert "Remove deprecated parameters (#5249)" (#5276)" (#5277)

This reverts commit 47e5a2cf96.

* Aggregate on demand for v0.11 (#5302)

* Add client implementation

* Update workspace

* Update server

* Update service

* Gaz

* Mocks

* Fixed validator tests

* Add round tirp tests

* Fixed subnet test

* Wait 1/3 on validator side

* Lint

* Comment

* Update committee cache

* Comment

* Update RPC

* Fixed test

* Nishant's comment

* Gaz

* Refresh ENR is for epoch

* Needs to be append

* Fixed duplication

* Tests

* Skip e2e

* Update beacon-chain/rpc/validator/aggregator.go

Co-Authored-By: shayzluf <thezluf@gmail.com>

* Apply suggestions from code review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: shayzluf <thezluf@gmail.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>

* Refactor Dynamic Subscriptions (#5318)

* clean up

* comment

* metrics

* fix

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Fix listindexed attestations and detect historic attestations (#5321)

* fix list indexed attestations

* fix tests

* goimports

* names

* Add check for slot == 0 (#5322)

* Change attester protection to return default if DB is empty (#5323)

* Change how default values are set

* Remove unused imports

* Remove wasteful db call

* Fix db tests

* Fix db test

* fix it (#5326)

* V0.11 run time fixes to use interop config (#5324)

* Started testing
* Bunch of fixes
* use-interop
* Sync with v0.11
* Conflict
* Uncomment wait for activation
* Move pending block queue from subscriber to validator pipeline
* Merge branch 'v0.11' into use-interop-config
* passing tests
* Merge refs/heads/v0.11 into use-interop-config
* Merge refs/heads/v0.11 into use-interop-config

* Nil Checks in Process Attestation v0.11 (#5331)

* Started testing

* Bunch of fixes

* use-interop

* Sync with v0.11

* Uncomment wait for activation

* Move pending block queue from subscriber to validator pipeline

* passing tests

* nil checks to prevent panics

* lint

Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* Validator batch subscribe subnets (#5332)

* Update both beacon node and validator

* Comments

* Tests

* Lint

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Validator smarter subscribe (#5334)

* Fix incorrect proposer index calculation (#5336)

* Use correct parent state

* Fixed test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* enhance error

* enhance error

* Update P2P Service to Handle Local Metadata (#5319)

* add metadata to ENR

* add new methods

* glue everything

* fix all tests and refs

* add tests

* add more tests

* Apply suggestions from code review

* fix method

* raul's review

* gaz

* fix test setup

* fix all tests

* better naming

* fix broken test

* validate nil

Co-authored-by: rauljordan <raul@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Revert "Revert "Revert "Remove deprecated parameters (#5249)" (#5276)" (#5277)" (#5343)

This reverts commit e5aef1686e.

* Wait for Genesis Event to Start P2P (#5303)

* use event feed for state initialized events

* add in handler for tests

* wait till genesis for p2p

* Apply suggestions from code review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Avoid duplicated aggregation request (#5346)

* Avoid duplicated aggregation request

* Test and lock

* Gaz

* Fix Validate For Metadata (#5348)

* return true

* shay's review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Multiple Proposer Slots Allowed Per Epoch for Validators (#5344)

* allow multiple proposer slots

* multi propose

* proposer indices to slots map

* remove deprecated comm assign

* Apply suggestions from code review

* resolve broken tests, add logic in validator client

* fix val tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Networking Fixes (#5349)

* close stream later

* add ping method

* add method

* lint

* More efficient aggregation on demand (#5354)

* Return Nil Error if Pre-Genesis in P2P Service Healthz Check (#5355)

* pregenesis healthz check:

* optimal

* right order

* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* no comment

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* Release DiscoveryV5 for Testnet Restart (#5357)

* release discv5

* fix build

* Fix Overflow in Status Check (#5361)

* fix overflow

* Apply suggestions from code review

* fix after merge

* Make Mainnet Config Default, No More Demo Config  (#5367)

* bye bye demo config

* gaz

* fix usage

* fix dep

* gaz

* Update default balance for sendDeposits

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* Use FastSSZ Marshal/Unmarshal for DB Encodings in v0.11.1 (#5351)

* try

* use marshaler structure for db instead of proto

* white list types

* attempt

* revert

* testutil.NewBeaconState()

* Fully populate fields for round trip ssz marshal

* fix //beacon-chain/db/kv:go_default_test

* more passing tests

* another test target passed

* fixed stategen

* blockchain tests green

* passing sync

* more targets fixed

* more test fixes in rpc/validator

* most rpc val

* validators test fixes

* skip round robin old

* aggregate test

* whitelist done

* Update beacon-chain/rpc/validator/attester_test.go

* edit baz

* Fixed tests

* Fixed getblock test

* Add back init

* reduce test size

* fix broken build

* tests pass

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* Reconnect slasher streams on beacon node shutdown (#5376)

* restart streams on beacon node shutdown

* fix comment

* remove export

* ivan feedback

* ivan feedback

* case insensitive

* Update slasher/beaconclient/receivers.go

* raul feedback

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Amend Faucet to Offer 32.5 ETH for v0.11 (#5378)

* deposit amount in faucet

* fix eth amount

* gas cost

* unskip exec transition test

* Revert "Enable NOISE Handshake by Default v0.11 (#5272)" (#5381)

This reverts commit a8d32d504a.

* use string for deposit flag

* Update Bootnode to v0.11 (#5387)

* fix bootnode

* add changes

* gaz

* fix docker

* build fix

* fix flaky test

* Unskip E2E for V0.11 (#5386)

* Begin work on fixing e2e for v0.11

* Start bootnode work

* Begin implementing bootnode into e2e

* Fix E2E for v0.11

* Remove extra

* gaz

* Remove unused key gen code

* Remove trailing multiaddr code

* add skip for slashing

* Fix slashing e2e

* Fix docker image build

* Update beacon-chain/p2p/broadcaster_test.go

* Update GetValidatorParticipation

* Update tests

* Gaz

* Pass E2E Tests for v0.11 and Enable Attestation Subnets By Default (#5407)

* Update README.md

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Apply suggestions from code review

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update beacon-chain/p2p/config.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update shared/keystore/deposit_input.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update tools/faucet/server.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update proto/beacon/p2p/v1/BUILD.bazel

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update shared/bls/spectest/aggregate_verify_test.go

* Addressed feedback. All test passing

* Update beacon-chain/core/blocks/block_operations_fuzz_test.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>

* Update beacon-chain/core/blocks/block_operations_test.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>

* Update shared/testutil/helpers.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>

* Update beacon-chain/core/helpers/signing_root.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>

* Resolve Misc v0.11 Items (Raul) (#5414)

* address all comments

* set faucet

* nishant feedback

* Update beacon-chain/p2p/service.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Revert keymanager changes (#5416)

* Revert "Updates for remote keymanager (#5260)"

This reverts commit bbcd895db5.

* Revert "Remove keystore keymanager from validator (#5236)"

This reverts commit 46008770c1.

* Revert "Update eth2 wallet keymanager (#4984)"

This reverts commit 7f7ef43f21.

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>

* Update BLS and limit visibility (#5415)

* remove duplicated BLS, add golang.org/x/mod

* Update BLS and restrict visibility

* fix build

* Fix eth1data test and fix order of ops (#5413)

* use multiaddr builder (#5419)

* Unskip benchutil and minor v0.11 fixes (#5417)

* Unskip benchutil tests

* Remove protos and gaz

* Fixes

* Networking Fixes (#5421)

* check

* fix test

* fix size

* fix test

* more fixes

* fix test again

* Update ethereum APIs with latest master

* Error handling for v0.11 tests (#5428)

* Proper err handling for tests

* Lint

* Fixed rest of the tests

* Gaz

* Fixed old master tests

* Rm old aggregate_test.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: nisdas <nishdas93@gmail.com>
Co-authored-by: Jim McDonald <Jim@mcdee.net>
Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: shayzluf <thezluf@gmail.com>
* Validator participation with fallback
* Add back the old tests
* Fixed test
* Merge branch 'master' into validator-participation-fallback
* Merge refs/heads/master into validator-participation-fallback
2020-04-20 01:39:15 +00:00
terence tsao
7d8516cd71 Add back archival endpoint ListValidatorAssignments with fallback (#5517)
* Modify `ListValidatorAssignments` to use new state service (#5365)

* Fixed rest of non spec tests
* Fixed a bug proposer index wasn't included
* gaz
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Updated eth1 data voting period to epoch based
* Fixed failed tests
* fix bug
* fix error
* Fixed more misc tests
* Add new SignedAggregateAndProof to pass spec test
* Update minimalConfig.PersistentCommitteePeriod
* allow to rebuild trie
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Skip e2e tests
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Align aggregator action with v0.11 (#5146)
* Remove Head Root from Beacon Block by Range Request (#5165)

* make proto changes
* remove head root
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into v0.11
* add back herumi's library
* Update ethapi in workspace, started fixing test. Hand off to Nishant
* fix build
* All tests passing
* Align finalized slot check with v0.11 (#5166)
* Merge branch 'master' into v0.11
* Add DoS resistance for v0.11 (#5158)
* Add Fork Digest Helper (#5173)
* Extend DoS prevention to rest of operation objects (#5174)

* Update mapping

* Add caches

* Update seen block in validation pipeline

* Update seen att in validation pipeline

* Update seen att in validation pipeline

* Fixed rest of tests

* Gazelle

* Better writes

* Lint

* Preston's feedback

* Switched to LRU cache and fixed tests

* Gazelle

* Fix test

* Update proposer slashing

* Update proposer slashing

* Fixed a block test

* Update exit

* Update atteser slashing

* Raul's feedback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Add remote keymanager (#5133)

* Add remote keymanager

* Add generic signRoot() helper

* Add tests for remote keymanager

* NewRemote -> NewRemoteWallet

* signRoot -> signOject, to increase reuse

* Fix end-to-end compile error

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Add Snappy Framing to the Encoder (#5172)

* change to framing

* more fixes

* fix everything

* add stricter limits

* preston feedback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: rauljordan <raul@prysmaticlabs.com>
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Move Subnet Functionality to its Own File (#5179)

* move subnets to their own file

* fix build fail

* build

* Update beacon-chain/p2p/discovery_test.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Sync with master
* Verify proposer signature in sync (#5206)
* Fix Signed Attestation In Sync (#5207)
* Add Eth2 Fork ENR Functionality (#5181)

* add fork entry enr

* add in fork

* add the required fork entry to node

* add and retrieve fork entry

* await state initialized

* utilize new structure

* more progress, utilizing a config map instead

* send the genesis validators root via the event feed

* struct method for discovery

* fix broken builds

* fixed up more tsts using state feed initializer

* fix up most tests

* only one more failing test

* almost done with tests

* p2p tests all pass

* config fix

* fix blockchain test

* gaz

* add in todo

* lint

* add compare func

* ensure fork ENR versions match between peers

* add in test for discovery

* test name

* tests complete

* tests done

* done

* comments

* fix all flakes

* addressed comments

* build using ssz gen

* marshal record

* use custom ssz

* deduplicate import

* fix build

* add enr proto

* p2p tests done

Co-authored-by: nisdas <nishdas93@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Verify aggregator signature in sync (#5208)
* Add Fork Digest For Gossip Topics (#5191)

* update for the day

* fix remaining failing test

* fix one more test

* change message

* Apply suggestions from code review

Co-Authored-By: terence tsao <terence@prysmaticlabs.com>

* terence's review

* implement fork digest'

* align digest to interface'

* passed all tests

* spawn in goroutine

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
* Fix Incorrect Attester Slashing Method (#5229)
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Remove keystore keymanager from validator (#5236)

* Remove keystore keymanager from validator

* Update dependency

* Update validator/flags/flags.go

* Update validator/flags/flags.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
* fix broadcaster
* update metrics with fork digest for p2p (#5251)

* update metrics with fork digest for p2p

* update p2p metrics

* update metrics using att values

* wrapped up

* fix bug

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Fix incorrect domain type comments (#5250)

* Fix incorrect domain type comments
* resolve conflicts
* fix broken broadcast test
* fix tests
* include protocol suffix
* fix confs
* lint
* fix test
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Merge branch 'master' of github.com:prysmaticlabs/prysm into v0.11
* resolve broken slasher test'
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Merge branch 'master' into v0.11
* fix config override
* Remove deprecated parameters (#5249)
* Avoid div by zero in extreme balance case (#5273)

* Return effective balance increment instead of 1

* Update to new spec tests v0.11.1

* Revert "Regen historical states for `new-state-mgmt` compatibility (#5261)"

This reverts commit df9a534826.

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Revert "Remove deprecated parameters (#5249)" (#5276)

This reverts commit 7d17c9ac34.
* Verify block proposer index before gossip  (#5274)

* Update pipeline

* Update tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Add in Proposer Index to Custom HTR (#5269)

* fix test

* Update beacon-chain/state/stateutil/blocks_test.go

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Resolve Flakey P2P Tests (#5285)

* double time for flakey test

* fix test flakeyness in p2p:

* flakey

* time tolerance

* greater tolerance
* Merge branch 'master' into v0.11
* release resources correctly (#5287)
* Merge refs/heads/master into v0.11
* Enable NOISE Handshake by Default v0.11 (#5272)

* noise handshakes by default

* fix build

* noisy noise everywhere

* deprecated noisy noise flag with more noise

* add secio as fallback

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: nisdas <nishdas93@gmail.com>
* Merge refs/heads/master into v0.11
* new ports
* fix broken build
* Make `new-state-mgmt` canonical  (#5289)

* Invert the flags
* Update checking messages
* Fixed all db tests
* Fixed rest of the block chain tests
* Fix chain race tests
* Fixed rpc tests
* Disable soudns better...
* Merge branch 'v0.11' into invert-new-state-mgmt
* Merge refs/heads/v0.11 into invert-new-state-mgmt
* Fix export
* Merge branch 'invert-new-state-mgmt' of github.com:prysmaticlabs/prysm into invert-new-state-mgmt
* Fix conflict tests
* Gazelle
* Merge refs/heads/v0.11 into invert-new-state-mgmt
* Merge refs/heads/v0.11 into invert-new-state-mgmt
* Merge branch 'master' into v0.11
* resolve flakeyness
* Merge refs/heads/master into v0.11
* Merge refs/heads/master into v0.11
* Detect Proposer Slashing Implementation (#5139)

* detect blocks

* detect blocks

* use stub

* use stub

* use stub

* todo

* fix test

* add tests and utils

* fix imports

* fix imports

* fix comment

* todo

* proposerIndex

* fix broken test

* formatting and simplified if

* Update slasher/detection/service.go

* Update slasher/detection/testing/utils.go

Co-Authored-By: terence tsao <terence@prysmaticlabs.com>

* fixed up final comments

* better naming

* Update slasher/detection/service.go

* Update slasher/detection/service.go

* Update slasher/detection/service.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>

* no more named args

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into v0.11
* Add Metadata And Ping RPC methods (#5271)

* add new proto files

* add flag and helper

* add initializer

* imports

* add ping method

* add receive/send ping request

* add ping test

* refactor rpc methods and add ping test

* finish adding all tests

* fix up tests

* Apply suggestions from code review

* lint

* imports

* lint

* Update beacon-chain/p2p/service.go

* Update shared/cmd/flags.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Merge branch 'master' of https://github.com/prysmaticlabs/geth-sharding into v0.11
* Updates for remote keymanager (#5260)
* Merge branch 'spec-v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Merge remote-tracking branch 'origin' into v0.11
* Update to slash by slot instead of epoch (#5297)

* change to slash by slot instead of epoch

* gaz

* fix test

* fix test

* fix infinite loop on error parse
* Sync with master
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Update proposer protection to v0.11 (#5292)

* Complete most of changes

* Fix other tests

* Test progress

* Tests

* Finish tests

* update pbs

* Fix mocked tests

* Gazelle

* pt 2

* Fix

* Fixes

* Fix tests wit hwrong copying
* Merge refs/heads/master into v0.11
* Merge refs/heads/master into v0.11
* Implement `SubscribeCommitteeSubnet` method (#5299)

* Add client implementation

* Update workspace

* Update server

* Update service

* Gaz

* Mocks

* Fixed validator tests

* Add round tirp tests

* Fixed subnet test

* Comment

* Update committee cache

* Comment

* Update RPC

* Fixed test

* Nishant's comment

* Gaz

* Refresh ENR is for epoch

* Needs to be append
* Merge refs/heads/master into v0.11
* resolve confs
* Validator subscribe subnet to next epoch (#5312)

* Alert to subscribe to next epoch

* Fixed tests

* Comments

* Fixed tests

* Update validator/client/validator.go

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Revert "Revert "Remove deprecated parameters (#5249)" (#5276)" (#5277)

This reverts commit 47e5a2cf96.
* Aggregate on demand for v0.11 (#5302)

* Add client implementation

* Update workspace

* Update server

* Update service

* Gaz

* Mocks

* Fixed validator tests

* Add round tirp tests

* Fixed subnet test

* Wait 1/3 on validator side

* Lint

* Comment

* Update committee cache

* Comment

* Update RPC

* Fixed test

* Nishant's comment

* Gaz

* Refresh ENR is for epoch

* Needs to be append

* Fixed duplication

* Tests

* Skip e2e

* Update beacon-chain/rpc/validator/aggregator.go

Co-Authored-By: shayzluf <thezluf@gmail.com>

* Apply suggestions from code review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: shayzluf <thezluf@gmail.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
* Refactor Dynamic Subscriptions (#5318)

* clean up

* comment

* metrics

* fix

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/master into v0.11
* Fix listindexed attestations and detect historic attestations (#5321)

* fix list indexed attestations

* fix tests

* goimports

* names
* Add check for slot == 0 (#5322)
* Change attester protection to return default if DB is empty (#5323)

* Change how default values are set

* Remove unused imports

* Remove wasteful db call

* Fix db tests

* Fix db test
* Merge refs/heads/master into v0.11
* fix it (#5326)
* V0.11 run time fixes to use interop config (#5324)

* Started testing
* Bunch of fixes
* use-interop
* Sync with v0.11
* Conflict
* Uncomment wait for activation
* Move pending block queue from subscriber to validator pipeline
* Merge branch 'v0.11' into use-interop-config
* passing tests
* Merge refs/heads/v0.11 into use-interop-config
* Merge refs/heads/v0.11 into use-interop-config
* Merge refs/heads/master into v0.11
* Merge refs/heads/master into v0.11
* Merge refs/heads/master into v0.11
* Nil Checks in Process Attestation v0.11 (#5331)

* Started testing

* Bunch of fixes

* use-interop

* Sync with v0.11

* Uncomment wait for activation

* Move pending block queue from subscriber to validator pipeline

* passing tests

* nil checks to prevent panics

* lint

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Validator batch subscribe subnets (#5332)

* Update both beacon node and validator

* Comments

* Tests

* Lint

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Validator smarter subscribe (#5334)
* Fix incorrect proposer index calculation (#5336)

* Use correct parent state

* Fixed test

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* enhance error
* enhance error
* Update P2P Service to Handle Local Metadata (#5319)

* add metadata to ENR

* add new methods

* glue everything

* fix all tests and refs

* add tests

* add more tests

* Apply suggestions from code review

* fix method

* raul's review

* gaz

* fix test setup

* fix all tests

* better naming

* fix broken test

* validate nil

Co-authored-by: rauljordan <raul@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Revert "Revert "Revert "Remove deprecated parameters (#5249)" (#5276)" (#5277)" (#5343)

This reverts commit e5aef1686e.
* Wait for Genesis Event to Start P2P (#5303)

* use event feed for state initialized events

* add in handler for tests

* wait till genesis for p2p

* Apply suggestions from code review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/master into v0.11
* Avoid duplicated aggregation request (#5346)

* Avoid duplicated aggregation request

* Test and lock

* Gaz
* Fix Validate For Metadata (#5348)

* return true

* shay's review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Multiple Proposer Slots Allowed Per Epoch for Validators (#5344)

* allow multiple proposer slots

* multi propose

* proposer indices to slots map

* remove deprecated comm assign

* Apply suggestions from code review

* resolve broken tests, add logic in validator client

* fix val tests

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Networking Fixes (#5349)

* close stream later

* add ping method

* add method

* lint
* More efficient aggregation on demand (#5354)
* Return Nil Error if Pre-Genesis in P2P Service Healthz Check (#5355)

* pregenesis healthz check:

* optimal

* right order

* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>

* no comment

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* STarting
* Release DiscoveryV5 for Testnet Restart (#5357)

* release discv5

* fix build
* Fix Overflow in Status Check (#5361)

* fix overflow

* Apply suggestions from code review
* Update assignments
* Genesis short circuit
* Fixed tests
* Merge branch 'master' of github.com:prysmaticlabs/prysm into v0.11
* fix after merge
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge refs/heads/master into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Make Mainnet Config Default, No More Demo Config  (#5367)

* bye bye demo config

* gaz

* fix usage

* fix dep

* gaz

* Update default balance for sendDeposits

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Use FastSSZ Marshal/Unmarshal for DB Encodings in v0.11.1 (#5351)

* try

* use marshaler structure for db instead of proto

* white list types

* attempt

* revert

* testutil.NewBeaconState()

* Fully populate fields for round trip ssz marshal

* fix //beacon-chain/db/kv:go_default_test

* more passing tests

* another test target passed

* fixed stategen

* blockchain tests green

* passing sync

* more targets fixed

* more test fixes in rpc/validator

* most rpc val

* validators test fixes

* skip round robin old

* aggregate test

* whitelist done

* Update beacon-chain/rpc/validator/attester_test.go

* edit baz

* Fixed tests

* Fixed getblock test

* Add back init

* reduce test size

* fix broken build

* tests pass

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Reconnect slasher streams on beacon node shutdown (#5376)

* restart streams on beacon node shutdown

* fix comment

* remove export

* ivan feedback

* ivan feedback

* case insensitive

* Update slasher/beaconclient/receivers.go

* raul feedback

Co-authored-by: Ivan Martinez <ivanthegreatdev@gmail.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge branch 'master' into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge refs/heads/master into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Amend Faucet to Offer 32.5 ETH for v0.11 (#5378)

* deposit amount in faucet

* fix eth amount

* gas cost
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* unskip exec transition test
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Revert "Enable NOISE Handshake by Default v0.11 (#5272)" (#5381)

This reverts commit a8d32d504a.
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge refs/heads/master into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* use string for deposit flag
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update Bootnode to v0.11 (#5387)

* fix bootnode

* add changes

* gaz

* fix docker
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Fixed conflict
* Merge branch 'master' of github.com:prysmaticlabs/prysm into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* build fix
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* fix flaky test
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge refs/heads/master into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into fix-list-validator-assignments
* Fixed more conflicts
* Merge branch 'fix-list-validator-assignments' of github.com:prysmaticlabs/prysm into fix-list-validator-assignments
* Unskip E2E for V0.11 (#5386)

* Begin work on fixing e2e for v0.11

* Start bootnode work

* Begin implementing bootnode into e2e

* Fix E2E for v0.11

* Remove extra

* gaz

* Remove unused key gen code

* Remove trailing multiaddr code

* add skip for slashing

* Fix slashing e2e

* Fix docker image build
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge refs/heads/master into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge branch 'master' of github.com:prysmaticlabs/prysm into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update beacon-chain/p2p/broadcaster_test.go
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into fix-list-validator-assignments
* Fixed test
* Merge branch 'fix-list-validator-assignments' of github.com:prysmaticlabs/prysm into fix-list-validator-assignments
* Merge refs/heads/master into v0.11
* Merge branch 'v0.11' into fix-list-validator-assignments
* Pass E2E Tests for v0.11 and Enable Attestation Subnets By Default (#5407)
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update README.md

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Apply suggestions from code review

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update beacon-chain/p2p/config.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update shared/keystore/deposit_input.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update tools/faucet/server.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update beacon-chain/p2p/service.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update proto/beacon/p2p/v1/BUILD.bazel

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update shared/benchutil/pregen_test.go

Co-Authored-By: Preston Van Loon <preston@prysmaticlabs.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update shared/bls/spectest/aggregate_verify_test.go
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Addressed feedback. All test passing
* Merge branch 'v0.11' of github.com:prysmaticlabs/prysm into v0.11
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update beacon-chain/core/blocks/block_operations_fuzz_test.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update beacon-chain/core/blocks/block_operations_test.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update shared/testutil/helpers.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update beacon-chain/core/helpers/signing_root.go

Co-Authored-By: Ivan Martinez <ivanthegreatdev@gmail.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Resolve Misc v0.11 Items (Raul) (#5414)

* address all comments

* set faucet

* nishant feedback

* Update beacon-chain/p2p/service.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Revert keymanager changes (#5416)

* Revert "Updates for remote keymanager (#5260)"

This reverts commit bbcd895db5.

* Revert "Remove keystore keymanager from validator (#5236)"

This reverts commit 46008770c1.

* Revert "Update eth2 wallet keymanager (#4984)"

This reverts commit 7f7ef43f21.

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update BLS and limit visibility (#5415)

* remove duplicated BLS, add golang.org/x/mod

* Update BLS and restrict visibility

* fix build
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Fix eth1data test and fix order of ops (#5413)
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* use multiaddr builder (#5419)
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Unskip benchutil and minor v0.11 fixes (#5417)

* Unskip benchutil tests

* Remove protos and gaz

* Fixes
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Networking Fixes (#5421)

* check

* fix test

* fix size

* fix test

* more fixes

* fix test again
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Update ethereum APIs with latest master
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Error handling for v0.11 tests (#5428)

* Proper err handling for tests

* Lint

* Fixed rest of the tests

* Gaz

* Fixed old master tests
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Sync with master
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Rm old aggregate_test.go
* Merge refs/heads/v0.11 into fix-list-validator-assignments
* Merge branch 'master' into fix-list-validator-assignments
* Fixed conflicts
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* Merge refs/heads/master into fix-list-validator-assignments
* List validator assignments with fallback
* Invert the flag
* Merge refs/heads/master into list-validator-assignment-fallback
2020-04-20 01:19:11 +00:00
Shay Zluf
95f1676d5f Fix broadcast slashing flag (#5515) 2020-04-19 16:41:59 -04:00
Ivan Martinez
42e6532d5b Fix prysm.sh for arm64 (#5511) 2020-04-19 11:58:01 -04:00
Shay Zluf
acd7dd137f More efficient list indexed attestation endpoint (#5441)
* use state gen to retrieve state fo computing committees

* gaz + goimports

* remove duplicate

* main net config

* committee instead of committee

* remove

* handle feature config

* Update beacon-chain/rpc/beacon/attestations.go

Co-Authored-By: Victor Farazdagi <simple.square@gmail.com>

* remove duplication

* group attestations by block root

* fix errors

* fix test

* ivan feedback

* add test

* return error if new state management is turned off

* fix featureconfig handling

* gaz

* Update beacon-chain/rpc/beacon/attestations.go

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
Co-authored-by: terence tsao <terence@prysmaticlabs.com>
2020-04-19 18:13:33 +03:00
Nishant Das
626b3e0c66 Add Reference Copying (#5245)
* add state changes
* add new changes
* add flag
* lint
* add flag
* change to correct bool
* fixing and consolidating trie
* lint
* Apply suggestions from code review
* Merge refs/heads/master into addBetterCopying
* Merge branch 'master' into addBetterCopying
* refCopy -> stateRefCopy
* Merge refs/heads/master into addBetterCopying
* tests whether unexpected mutation of validators within state is avoided
* Merge branch 'addBetterCopying' of github.com:prysmaticlabs/prysm into addBetterCopying
* remove unnecessary fields
* gazelle
* updates test
* avoid unexpected mutation in block roots on refcopy
* avoid unexpected mutation in state roots on refcopy
* Merge refs/heads/master into addBetterCopying
* Merge branch 'master' into addBetterCopying
* fix test
* randao tests
* simplify tests
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* test cur/prev attestations mutation
* Merge branch 'addBetterCopying' of github.com:prysmaticlabs/prysm into addBetterCopying
* gazelle
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* fixes tests
* minor naming update
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
* Merge refs/heads/master into addBetterCopying
2020-04-19 13:57:43 +00:00
Ivan Martinez
dee3f02e2c Change prometheus port for different parts of Prysm (#5504)
* Change prometheus flag from default 8080 and sort flags
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into change-prometheus-port
* Fix build
* Merge branch 'master' of https://github.com/prysmaticlabs/prysm into change-prometheus-port
* Merge branch 'master' into change-prometheus-port
2020-04-19 08:36:19 +00:00
Ivan Martinez
f2d88ea920 Fix prysm.sh for arm64 (#5507)
* Fix prysm script for arm
2020-04-19 08:15:52 +00:00
1186 changed files with 84378 additions and 43043 deletions

View File

@@ -5,6 +5,9 @@ test --test_verbose_timeout_warnings
test --build_tests_only
test --test_output=errors
# Clearly indicate that coverage is enabled to disable certain nogo checks.
coverage --define=coverage_enabled=1
# Fix for rules_docker. See: https://github.com/bazelbuild/rules_docker/issues/842
build --host_force_python=PY2
test --host_force_python=PY2
@@ -30,20 +33,60 @@ build --define kafka_enabled=false
test --define kafka_enabled=false
run --define kafka_enabled=false
build:kafka_enabled --define kafka_enabled=true
build:kafka_enabled --define gotags=kafka_enabled
# Release flags
build:release --workspace_status_command=./scripts/workspace_status.sh
build:release --stamp
build:release --compilation_mode=opt
build:release --config=llvm
# LLVM compiler for building C/C++ dependencies.
build:llvm --crosstool_top=@llvm_toolchain//:toolchain
build:llvm --define compiler=llvm
build:llvm --copt -fno-sanitize=vptr,function
build:llvm --linkopt -fno-sanitize=vptr,function
build:asan --copt -fsanitize=address,undefined
build:asan --copt -fno-omit-frame-pointer
build:asan --linkopt -fsanitize=address,undefined
build:asan --copt -fno-sanitize=vptr,function
build:asan --linkopt -fno-sanitize=vptr,function
build:asan --copt -DADDRESS_SANITIZER=1
build:asan --copt -D__SANITIZE_ADDRESS__
build:asan --linkopt -ldl
build:llvm-asan --config=llvm
build:llvm-asan --config=asan
build:llvm-asan --linkopt -fuse-ld=ld.lld
build:fuzz --define=gotags=libfuzzer
build:fuzz --config=llvm-asan
build:fuzz --copt=-fsanitize=fuzzer-no-link
build:fuzz --linkopt=-fsanitize=fuzzer
build:fuzz --copt=-fno-omit-frame-pointer
build:fuzz --define=FUZZING_ENGINE=libfuzzer
build:fuzz --copt=-DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
build:fuzz --linkopt -Wl,--no-as-needed
build:fuzz --define=gc_goopts=-d=libfuzzer
build:fuzz --run_under=//tools:fuzz_wrapper
build:fuzz --compilation_mode=opt
test:fuzz --local_test_jobs="HOST_CPUS*.5"
test:fuzzit --config=fuzz
test:fuzzit --test_env=FUZZIT_API_KEY
test:fuzzit --test_env=PRYSM_BUILD_IMAGE=gcr.io/prysmaticlabs/prysm-fuzzit:v0.11.0
test:fuzzit --test_timeout=1200
test:fuzzit --run_under=//tools:fuzzit_wrapper
# Build binary with cgo symbolizer for debugging / profiling.
build:cgo_symbolizer --config=llvm
build:cgo_symbolizer --copt=-g
build:cgo_symbolizer --define=USE_CGO_SYMBOLIZER=true
build:cgo_symbolizer -c dbg
build:cgo_symbolizer --define=gotags=cgosymbolizer_enabled
# multi-arch cross-compiling toolchain configs:
-----------------------------------------------

View File

@@ -1 +1 @@
3.0.0
3.2.0

View File

@@ -2,24 +2,14 @@
# across machines, developers, and workspaces.
#
# This config is loaded from https://github.com/bazelbuild/bazel-toolchains/blob/master/bazelrc/latest.bazelrc
build:remote-cache --remote_cache=grpcs://remotebuildexecution.googleapis.com
build:remote-cache --remote_timeout=3600
build:remote-cache --auth_enabled=true
build:remote-cache --spawn_strategy=standalone
build:remote-cache --strategy=Javac=standalone
build:remote-cache --strategy=Closure=standalone
build:remote-cache --strategy=Genrule=standalone
# Build results backend.
#build:remote-cache --bes_results_url="https://source.cloud.google.com/results/invocations/"
#build:remote-cache --bes_backend=buildeventservice.googleapis.com
#build:remote-cache --bes_timeout=60s
#build:remote-cache --project_id=prysmaticlabs
# Prysm specific remote-cache properties.
build:remote-cache --disk_cache=
build:remote-cache --host_platform_remote_properties_override='properties:{name:\"cache-silo-key\" value:\"prysm\"}'
build:remote-cache --remote_instance_name=projects/prysmaticlabs/instances/default_instance
#build:remote-cache --disk_cache=
build:remote-cache --remote_download_minimal
# Import workspace options.
@@ -45,7 +35,15 @@ build --flaky_test_attempts=5
# build --features=race
# Enable kafka for CI tests only.
test --define kafka_enabled=true
test --config=kafka_enabled
build --bes_backend=grpcs://builds.prylabs.net:1985
build --bes_results_url=https://builds.prylabs.net/invocation/
# Disable flaky test detection for fuzzing.
test:fuzz --flaky_test_attempts=1
# Expose test environment variables in CI
test:fuzzit --test_env=GITHUB_REF
test:fuzzit --test_env=GITHUB_SHA
test:fuzzit --test_env=DOCKER_HOST

3
.github/CODEOWNERS vendored
View File

@@ -3,3 +3,6 @@
# Starlark code owners
*.bzl @prestonvanloon
# Anyone on prylabs team can approve dependency updates.
deps.bzl @prysmaticlabs/core-team

38
.github/ISSUE_TEMPLATE/feature_flag.md vendored Normal file
View File

@@ -0,0 +1,38 @@
---
name: "\U0001F984Feature Flag Tracking"
about: Track a new feature, in development, in Prysm. This issue template should only be used by developers or contributors!
labels: Tracking
---
<!--💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎
Hellooo! 😄
Thanks for taking the time to file a tracking issue for your new feature. These issues really help
us track progress of features as they work their way through development. Be sure to review
shared/featureconfig/README.md for the latest documentation around feature flags.
💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎💎-->
# 🦄 Feature Tracking
**Current status** (opt-in or opt-out):
**Opt-in feature flag name**:
**Opt-out feature flag name**:
### Feature Description
<!-- ✍️--> A clear and concise description of the new feature. Provide links to your technical
design document or other supporting information.
### Tasks
- [ ] Feature flag created as opt-in
- [ ] Feature implemented / code complete
- [ ] Feature tested in production for adequate amount of time
- [ ] Feature flag is inverted to be opt-out and the opt-in flag is deprecated
- [ ] Feature has made it to a tagged production release as an opt-out flag
- [ ] Opt-out feature flag is deprecated and old code paths are cleaned up
This issue should be closed after all of the above tasks are complete.

30
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,30 @@
<!-- Thanks for sending a PR! Before submitting:
1. If this is your first PR, please read CONTRIBUTING.md and sign the CLA
first. We cannot review code without a signed CLA.
2. Please file an issue *first*. All features and most bug fixes should have
an associated issue with a design discussed and decided upon. Small bug
fixes and documentation improvements don't need issues.
3. New features and bug fixes must have tests. Documentation may need to
be updated. If you're unsure what to update, send the PR, and we'll discuss
in review.
4. Note that PRs updating dependencies and new Go versions are not accepted.
Please file an issue instead.
-->
**What type of PR is this?**
> Uncomment one line below and remove others.
>
> Bug fix
> Feature
> Documentation
> Other
**What does this PR do? Why is it needed?**
**Which issues(s) does this PR fix?**
Fixes #
**Other notes for review**

5
.github/actions/gofmt/Dockerfile vendored Normal file
View File

@@ -0,0 +1,5 @@
FROM cytopia/gofmt
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

12
.github/actions/gofmt/action.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
name: 'Gofmt checker'
description: 'Checks that all project files have been properly formatted.'
inputs:
path:
description: 'Path to check'
required: true
default: './'
runs:
using: 'docker'
image: 'Dockerfile'
args:
- ${{ inputs.path }}

15
.github/actions/gofmt/entrypoint.sh vendored Executable file
View File

@@ -0,0 +1,15 @@
#!/bin/sh -l
set -e
cd $GITHUB_WORKSPACE
# Check if any files are not formatted.
nonformatted="$(gofmt -l $1 2>&1)"
# Return if `go fmt` passes.
[ -z "$nonformatted" ] && exit 0
# Notify of issues with formatting.
echo "Following files need to be properly formatted:"
echo "$nonformatted"
exit 1

5
.github/actions/gomodtidy/Dockerfile vendored Normal file
View File

@@ -0,0 +1,5 @@
FROM golang:alpine
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

5
.github/actions/gomodtidy/action.yml vendored Normal file
View File

@@ -0,0 +1,5 @@
name: 'Go mod tidy checker'
description: 'Checks that `go mod tidy` has been applied.'
runs:
using: 'docker'
image: 'Dockerfile'

34
.github/actions/gomodtidy/entrypoint.sh vendored Executable file
View File

@@ -0,0 +1,34 @@
#!/bin/sh -l
set -e
export PATH=$PATH:/usr/local/go/bin
cd $GITHUB_WORKSPACE
cp go.mod go.mod.orig
cp go.sum go.sum.orig
go mod tidy
echo "Checking go.mod and go.sum:"
checks=0
if [ "$(diff -s go.mod.orig go.mod | grep -c 'Files go.mod.orig and go.mod are identical')" = 1 ]; then
echo "- go.mod is up to date."
checks=$((checks + 1))
else
echo "- go.mod is NOT up to date."
fi
if [ "$(diff -s go.sum.orig go.sum | grep -c 'Files go.sum.orig and go.sum are identical')" = 1 ]; then
echo "- go.sum is up to date."
checks=$((checks + 1))
else
echo "- go.sum is NOT up to date."
fi
if [ $checks -eq 2 ]; then
exit 0
fi
# Notify of any issues.
echo "Run 'go mod tidy' to update."
exit 1

50
.github/workflows/go.yml vendored Normal file
View File

@@ -0,0 +1,50 @@
name: Go
on:
push:
branches: [ master ]
pull_request:
branches: [ '*' ]
jobs:
check:
name: Check
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Go mod tidy checker
id: gomodtidy
uses: ./.github/actions/gomodtidy
- name: Gofmt checker
id: gofmt
uses: ./.github/actions/gofmt
with:
path: ./
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.x
uses: actions/setup-go@v2
with:
go-version: ^1.14
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Get dependencies
run: |
go get -v -t -d ./...
- name: Build
run: go build -v ./...
# Tests run via Bazel for now...
# - name: Test
# run: go test -v ./...

4
.gitignore vendored
View File

@@ -27,9 +27,5 @@ yarn-error.log
# Ignore password file
password.txt
# go dependancy
/go.mod
/go.sum
# Dist files
dist

View File

@@ -4,6 +4,7 @@ load("@com_github_atlassian_bazel_tools//goimports:def.bzl", "goimports")
load("@io_kubernetes_build//defs:run_in_workspace.bzl", "workspace_binary")
load("@io_bazel_rules_go//go:def.bzl", "nogo")
load("@graknlabs_bazel_distribution//common:rules.bzl", "assemble_targz", "assemble_versioned")
load("@bazel_skylib//rules:common_settings.bzl", "string_setting")
prefix = "github.com/prysmaticlabs/prysm"
@@ -12,6 +13,8 @@ exports_files([
])
# gazelle:prefix github.com/prysmaticlabs/prysm
# gazelle:map_kind go_library go_library @prysm//tools/go:def.bzl
# gazelle:map_kind go_repository go_repository @prysm//tools/go:def.bzl
gazelle(
name = "gazelle",
prefix = prefix,
@@ -43,7 +46,7 @@ alias(
# Protobuf gRPC gateway compiler
alias(
name = "grpc_gateway_proto_compiler",
actual = "@grpc_ecosystem_grpc_gateway//protoc-gen-grpc-gateway:go_gen_grpc_gateway",
actual = "@com_github_grpc_ecosystem_grpc_gateway//protoc-gen-grpc-gateway:go_gen_grpc_gateway",
visibility = ["//visibility:public"],
)
@@ -85,15 +88,12 @@ nogo(
"@org_golang_x_tools//go/analysis/passes/pkgfact:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/nilness:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/nilfunc:go_tool_library",
# lost cancel ignore doesn't seem to work when running with coverage
#"@org_golang_x_tools//go/analysis/passes/lostcancel:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/loopclosure:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/httpresponse:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/findcall:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/deepequalerrors:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/ctrlflow:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/copylock:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/composite:go_tool_library",
# "@org_golang_x_tools//go/analysis/passes/cgocall:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/buildtag:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/buildssa:go_tool_library",
@@ -105,8 +105,22 @@ nogo(
"@org_golang_x_tools//go/analysis/passes/asmdecl:go_tool_library",
"//tools/analyzers/maligned:go_tool_library",
"//tools/analyzers/roughtime:go_tool_library",
"//tools/analyzers/cryptorand:go_tool_library",
"//tools/analyzers/errcheck:go_tool_library",
],
"//tools/analyzers/featureconfig:go_tool_library",
] + select({
# nogo checks that fail with coverage enabled.
":coverage_enabled": [],
"//conditions:default": [
"@org_golang_x_tools//go/analysis/passes/lostcancel:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/composite:go_tool_library",
],
}),
)
config_setting(
name = "coverage_enabled",
values = {"define": "coverage_enabled=1"},
)
common_files = {
@@ -119,3 +133,12 @@ toolchain(
toolchain = "@rules_foreign_cc//tools/build_defs/native_tools:built_cmake",
toolchain_type = "@rules_foreign_cc//tools/build_defs:cmake_toolchain",
)
string_setting(
name = "gotags",
build_setting_default = "",
values = [
"",
"libfuzzer",
],
)

View File

@@ -1,6 +1,8 @@
# Contribution Guidelines
Excited by our work and want to get involved in building out our sharding releases? Or maybe you haven't learned as much about the Ethereum protocol but are a savvy developer? Our [READINGS.md](https://github.com/prysmaticlabs/prysm/blob/master/docs/READINGS.md) doc includes comprehensive information on Ethereum and sharding for both part-time and core contributors to the project.
Note: The latest and most up to date documenation can be found on our [docs portal](https://docs.prylabs.network/docs/contribute/contribution-guidelines).
Excited by our work and want to get involved in building out our sharding releases? Or maybe you haven't learned as much about the Ethereum protocol but are a savvy developer?
You can explore our [Open Issues](https://github.com/prysmaticlabs/prysm/issues) in-the works for our different releases. Feel free to fork our repo and start creating PRs after assigning yourself to an issue of interest. We are always chatting on [Discord](https://discord.gg/che9auJ) or [Gitter](https://gitter.im/prysmaticlabs/geth-sharding) drop us a line there if you want to get more involved or have any questions on our implementation!

69
DEPENDENCIES.md Normal file
View File

@@ -0,0 +1,69 @@
# Dependency Managagement in Prysm
Prysm is go project with many complicated dependencies, including some c++ based libraries. There
are two parts to Prysm's dependency management. Go modules and bazel managed dependencies. Be sure
to read [Why Bazel?](https://github.com/prysmaticlabs/documentation/issues/138) to fully
understand the reasoning behind an additional layer of build tooling via Bazel rather than a pure
"go build" project.
## Go Module support
The Prysm project officially supports go modules with some caveats.
### Caveat 1: Some c++ libraries are precompiled archives
Given some of Prysm's c++ dependencies have very complicated project structures which make building
difficult or impossible with "go build" alone. Additionally, building c++ dependencies with certain
compilers, like clang / LLVM, offer a significant performance improvement. To get around this
issue, c++ dependencies have been precompiled as linkable archives. While there isn't necessarily
anything bad about precompiled archives, these files are a "blackbox" which a 3rd party author
could have compiled anything for this archive and detecting undesired behavior would be nearly
impossible. If your risk tolerance is low, always compile everything from source yourself,
including complicated c++ dependencies.
*Recommendation: Use go build only for local development and use bazel build for production.*
### Caveat 2: Generated gRPC protobuf libraries
One key advantage of Bazel over vanilla `go build` is that Bazel automatically (re)builds generated
pb.go files at build time when file changes are present in any protobuf definition file or after
any updates to the protobuf compiler or other relevant dependencies. Vanilla go users should run
the following scripts often to ensure their generated files are up to date. Further more, Prysm
generates SSZ marshal related code based on defined data structures. These generated files must
also be updated and checked in as frequently.
```bash
./scripts/update-go-pbs.sh
./scripts/update-go-ssz.sh
```
*Recommendation: Use go build only for local development and use bazel build for production.*
### Caveat 3: Compile-time optimizations
When Prysmatic Labs builds production binaries, they use the "release" configuration of bazel to
compile with several compiler optimizations and recommended production build configurations.
Additionally, the release build properly stamps the built binaries to include helpful metadata
about how and when the binary was built.
*Recommendation: Use go build only for local development and use bazel build for production.*
```bash
bazel build //beacon-chain --config=release
```
## Adding / updating dependencies
1. Add your dependency as you would with go modules. I.e. `go get ...`
1. Run `gazelle update-repos -from_file=go.mod` to update the bazel managed dependencies.
Example:
```bash
go get github.com/prysmaticlabs/example@v1.2.3
bazel run //:gazelle -- update-repos -from_file=go.mod -to_macro=deps.bzl%prysm_deps
```
The deps.bzl file should have been updated with the dependency and any transitive dependencies.
Do NOT add new `go_repository` to the WORKSPACE file. All dependencies should live in deps.bzl.

View File

@@ -1,13 +0,0 @@
TODO(you): choose "part of" or "resolves" and the associated github issue #.
[Part of|Resolves] #531
---
# Description
**Write why you are making the changes in this pull request**
**Write a summary of the changes you are making**
**Link anything that would be helpful or relevant to the reviewers**

View File

@@ -1,7 +1,8 @@
# Prysm: An Ethereum 2.0 Client Written in Go
[![Build status](https://badge.buildkite.com/b555891daf3614bae4284dcf365b2340cefc0089839526f096.svg?branch=master)](https://buildkite.com/prysmatic-labs/prysm)
[![ETH2.0_Spec_Version 0.11.1](https://img.shields.io/badge/ETH2.0%20Spec%20Version-v0.11.1-blue.svg)](https://github.com/ethereum/eth2.0-specs/tree/v0.11.1)
[![fuzzit](https://app.fuzzit.dev/badge?org_id=prysmaticlabs-gh)](https://app.fuzzit.dev/orgs/prysmaticlabs-gh/dashboard)
[![ETH2.0_Spec_Version 0.12.2](https://img.shields.io/badge/ETH2.0%20Spec%20Version-v0.12.2-blue.svg)](https://github.com/ethereum/eth2.0-specs/tree/v0.12.2)
[![Discord](https://user-images.githubusercontent.com/7288322/34471967-1df7808a-efbb-11e7-9088-ed0b04151291.png)](https://discord.gg/KSA7rPr)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/prysmaticlabs/geth-sharding?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)

1530
WORKSPACE

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test")
load("@prysm//tools/go:def.bzl", "go_library")
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_test")
load("@io_bazel_rules_docker//go:image.bzl", "go_image")
load("@io_bazel_rules_docker//container:container.bzl", "container_bundle")
load("//tools:go_image.bzl", "go_image_alpine", "go_image_debug")
@@ -19,16 +20,15 @@ go_library(
"//shared/debug:go_default_library",
"//shared/featureconfig:go_default_library",
"//shared/logutil:go_default_library",
"//shared/maxprocs:go_default_library",
"//shared/version:go_default_library",
"@com_github_ethereum_go_ethereum//log:go_default_library",
"@com_github_ipfs_go_log//:go_default_library",
"@com_github_ipfs_go_log_v2//:go_default_library",
"@com_github_joonix_log//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@com_github_whyrusleeping_go_logging//:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
"@com_github_urfave_cli_v2//altsrc:go_default_library",
"@com_github_x_cray_logrus_prefixed_formatter//:go_default_library",
"@in_gopkg_urfave_cli_v2//:go_default_library",
"@in_gopkg_urfave_cli_v2//altsrc:go_default_library",
"@org_uber_go_automaxprocs//:go_default_library",
],
)
@@ -59,14 +59,13 @@ go_image(
"//shared/logutil:go_default_library",
"//shared/version:go_default_library",
"@com_github_ethereum_go_ethereum//log:go_default_library",
"@com_github_ipfs_go_log//:go_default_library",
"@com_github_ipfs_go_log_v2//:go_default_library",
"@com_github_joonix_log//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@com_github_whyrusleeping_go_logging//:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
"@com_github_urfave_cli_v2//altsrc:go_default_library",
"@com_github_x_cray_logrus_prefixed_formatter//:go_default_library",
"@in_gopkg_urfave_cli_v2//:go_default_library",
"@in_gopkg_urfave_cli_v2//altsrc:go_default_library",
"@org_uber_go_automaxprocs//:go_default_library",
"//shared/maxprocs:go_default_library",
],
)
@@ -75,6 +74,8 @@ container_bundle(
images = {
"gcr.io/prysmaticlabs/prysm/beacon-chain:latest": ":image",
"gcr.io/prysmaticlabs/prysm/beacon-chain:{DOCKER_TAG}": ":image",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:latest": ":image",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:{DOCKER_TAG}": ":image",
},
tags = ["manual"],
)
@@ -90,6 +91,8 @@ container_bundle(
images = {
"gcr.io/prysmaticlabs/prysm/beacon-chain:latest-debug": ":image_debug",
"gcr.io/prysmaticlabs/prysm/beacon-chain:{DOCKER_TAG}-debug": ":image_debug",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:latest-debug": ":image_debug",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:{DOCKER_TAG}-debug": ":image_debug",
},
tags = ["manual"],
)
@@ -105,6 +108,8 @@ container_bundle(
images = {
"gcr.io/prysmaticlabs/prysm/beacon-chain:latest-alpine": ":image_alpine",
"gcr.io/prysmaticlabs/prysm/beacon-chain:{DOCKER_TAG}-alpine": ":image_alpine",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:latest-alpine": ":image_alpine",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:{DOCKER_TAG}-alpine": ":image_alpine",
},
tags = ["manual"],
)
@@ -143,6 +148,6 @@ go_test(
embed = [":go_default_library"],
deps = [
"//shared/featureconfig:go_default_library",
"@in_gopkg_urfave_cli_v2//:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
],
)

View File

@@ -1,45 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = ["service.go"],
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/archiver",
visibility = ["//beacon-chain:__subpackages__"],
deps = [
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/feed:go_default_library",
"//beacon-chain/core/feed/state:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/core/validators:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/state:go_default_library",
"//proto/beacon/p2p/v1:go_default_library",
"//shared/params:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["service_test.go"],
embed = [":go_default_library"],
deps = [
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/core/epoch/precompute:go_default_library",
"//beacon-chain/core/feed:go_default_library",
"//beacon-chain/core/feed/state:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/db/testing:go_default_library",
"//beacon-chain/state:go_default_library",
"//proto/beacon/p2p/v1:go_default_library",
"//shared/params:go_default_library",
"//shared/testutil:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@com_github_sirupsen_logrus//hooks/test:go_default_library",
],
)

View File

@@ -1,200 +0,0 @@
package archiver
import (
"context"
"fmt"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/sirupsen/logrus"
)
var log = logrus.WithField("prefix", "archiver")
// Service defining archiver functionality for persisting checkpointed
// beacon chain information to a database backend for historical purposes.
type Service struct {
ctx context.Context
cancel context.CancelFunc
beaconDB db.NoHeadAccessDatabase
headFetcher blockchain.HeadFetcher
participationFetcher blockchain.ParticipationFetcher
stateNotifier statefeed.Notifier
lastArchivedEpoch uint64
}
// Config options for the archiver service.
type Config struct {
BeaconDB db.NoHeadAccessDatabase
HeadFetcher blockchain.HeadFetcher
ParticipationFetcher blockchain.ParticipationFetcher
StateNotifier statefeed.Notifier
}
// NewArchiverService initializes the service from configuration options.
func NewArchiverService(ctx context.Context, cfg *Config) *Service {
ctx, cancel := context.WithCancel(ctx)
return &Service{
ctx: ctx,
cancel: cancel,
beaconDB: cfg.BeaconDB,
headFetcher: cfg.HeadFetcher,
participationFetcher: cfg.ParticipationFetcher,
stateNotifier: cfg.StateNotifier,
}
}
// Start the archiver service event loop.
func (s *Service) Start() {
go s.run(s.ctx)
}
// Stop the archiver service event loop.
func (s *Service) Stop() error {
defer s.cancel()
return nil
}
// Status reports the healthy status of the archiver. Returning nil means service
// is correctly running without error.
func (s *Service) Status() error {
return nil
}
// We archive committee information pertaining to the head state's epoch.
func (s *Service) archiveCommitteeInfo(ctx context.Context, headState *state.BeaconState, epoch uint64) error {
proposerSeed, err := helpers.Seed(headState, epoch, params.BeaconConfig().DomainBeaconProposer)
if err != nil {
return errors.Wrap(err, "could not generate seed")
}
attesterSeed, err := helpers.Seed(headState, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return errors.Wrap(err, "could not generate seed")
}
info := &pb.ArchivedCommitteeInfo{
ProposerSeed: proposerSeed[:],
AttesterSeed: attesterSeed[:],
}
if err := s.beaconDB.SaveArchivedCommitteeInfo(ctx, epoch, info); err != nil {
return errors.Wrap(err, "could not archive committee info")
}
return nil
}
// We archive active validator set changes that happened during the previous epoch.
func (s *Service) archiveActiveSetChanges(ctx context.Context, headState *state.BeaconState, epoch uint64) error {
prevEpoch := epoch - 1
vals := headState.Validators()
activations := validators.ActivatedValidatorIndices(prevEpoch, vals)
slashings := validators.SlashedValidatorIndices(prevEpoch, vals)
activeValidatorCount, err := helpers.ActiveValidatorCount(headState, prevEpoch)
if err != nil {
return errors.Wrap(err, "could not get active validator count")
}
exited, err := validators.ExitedValidatorIndices(prevEpoch, vals, activeValidatorCount)
if err != nil {
return errors.Wrap(err, "could not determine exited validator indices")
}
activeSetChanges := &pb.ArchivedActiveSetChanges{
Activated: activations,
Exited: exited,
Slashed: slashings,
}
if err := s.beaconDB.SaveArchivedActiveValidatorChanges(ctx, prevEpoch, activeSetChanges); err != nil {
return errors.Wrap(err, "could not archive active validator set changes")
}
return nil
}
// We compute participation metrics by first retrieving the head state and
// matching validator attestations during the epoch.
func (s *Service) archiveParticipation(ctx context.Context, epoch uint64) error {
p := s.participationFetcher.Participation(epoch)
participation := &ethpb.ValidatorParticipation{}
if p != nil {
participation = &ethpb.ValidatorParticipation{
EligibleEther: p.PrevEpoch,
VotedEther: p.PrevEpochTargetAttesters,
GlobalParticipationRate: float32(p.PrevEpochTargetAttesters) / float32(p.PrevEpoch),
}
}
return s.beaconDB.SaveArchivedValidatorParticipation(ctx, epoch, participation)
}
// We archive validator balances and active indices.
func (s *Service) archiveBalances(ctx context.Context, balances []uint64, epoch uint64) error {
if err := s.beaconDB.SaveArchivedBalances(ctx, epoch, balances); err != nil {
return errors.Wrap(err, "could not archive balances")
}
return nil
}
func (s *Service) run(ctx context.Context) {
stateChannel := make(chan *feed.Event, 1)
stateSub := s.stateNotifier.StateFeed().Subscribe(stateChannel)
defer stateSub.Unsubscribe()
for {
select {
case event := <-stateChannel:
if event.Type == statefeed.BlockProcessed {
data, ok := event.Data.(*statefeed.BlockProcessedData)
if !ok {
log.Error("Event feed data is not type *statefeed.BlockProcessedData")
continue
}
log.WithField("headRoot", fmt.Sprintf("%#x", data.BlockRoot)).Debug("Received block processed event")
headState, err := s.headFetcher.HeadState(ctx)
if err != nil {
log.WithError(err).Error("Head state is not available")
continue
}
slot := headState.Slot()
currentEpoch := helpers.SlotToEpoch(slot)
if !helpers.IsEpochEnd(slot) && currentEpoch <= s.lastArchivedEpoch {
continue
}
epochToArchive := currentEpoch
if !helpers.IsEpochEnd(slot) {
epochToArchive--
}
if err := s.archiveCommitteeInfo(ctx, headState, epochToArchive); err != nil {
log.WithError(err).Error("Could not archive committee info")
continue
}
if err := s.archiveActiveSetChanges(ctx, headState, epochToArchive); err != nil {
log.WithError(err).Error("Could not archive active validator set changes")
continue
}
if err := s.archiveParticipation(ctx, epochToArchive); err != nil {
log.WithError(err).Error("Could not archive validator participation")
continue
}
if err := s.archiveBalances(ctx, headState.Balances(), epochToArchive); err != nil {
log.WithError(err).Error("Could not archive validator balances and active indices")
continue
}
log.WithField(
"epoch",
epochToArchive,
).Debug("Successfully archived beacon chain data during epoch")
s.lastArchivedEpoch = epochToArchive
}
case <-s.ctx.Done():
log.Debug("Context closed, exiting goroutine")
return
case err := <-stateSub.Err():
log.WithError(err).Error("Subscription to state feed notifier failed")
return
}
}
}

View File

@@ -1,483 +0,0 @@
package archiver
import (
"context"
"fmt"
"io/ioutil"
"reflect"
"testing"
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
dbutil "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/sirupsen/logrus"
logTest "github.com/sirupsen/logrus/hooks/test"
)
func init() {
logrus.SetLevel(logrus.DebugLevel)
logrus.SetOutput(ioutil.Discard)
}
func TestArchiverService_ReceivesBlockProcessedEvent(t *testing.T) {
hook := logTest.NewGlobal()
svc, beaconDB := setupService(t)
defer dbutil.TeardownDB(t, beaconDB)
st := testutil.NewBeaconState()
if err := st.SetSlot(1); err != nil {
t.Fatal(err)
}
svc.headFetcher = &mock.ChainService{
State: st,
}
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
triggerStateEvent(t, svc, event)
testutil.AssertLogsContain(t, hook, fmt.Sprintf("%#x", event.Data.(*statefeed.BlockProcessedData).BlockRoot))
testutil.AssertLogsContain(t, hook, "Received block processed event")
}
func TestArchiverService_OnlyArchiveAtEpochEnd(t *testing.T) {
hook := logTest.NewGlobal()
svc, beaconDB := setupService(t)
defer dbutil.TeardownDB(t, beaconDB)
// The head state is NOT an epoch end.
st := testutil.NewBeaconState()
if err := st.SetSlot(params.BeaconConfig().SlotsPerEpoch - 2); err != nil {
t.Fatal(err)
}
svc.headFetcher = &mock.ChainService{
State: st,
}
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
triggerStateEvent(t, svc, event)
// The context should have been canceled.
if svc.ctx.Err() != context.Canceled {
t.Error("context was not canceled")
}
testutil.AssertLogsContain(t, hook, "Received block processed event")
// The service should ONLY log any archival logs if we receive a
// head slot that is an epoch end.
testutil.AssertLogsDoNotContain(t, hook, "Successfully archived")
}
func TestArchiverService_ArchivesEvenThroughSkipSlot(t *testing.T) {
hook := logTest.NewGlobal()
svc, beaconDB := setupService(t)
validatorCount := uint64(100)
headState, err := setupState(validatorCount)
if err != nil {
t.Fatal(err)
}
defer dbutil.TeardownDB(t, beaconDB)
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
exitRoutine := make(chan bool)
go func() {
svc.run(svc.ctx)
<-exitRoutine
}()
// Send out an event every slot, skipping the end slot of the epoch.
for i := uint64(0); i < params.BeaconConfig().SlotsPerEpoch+1; i++ {
if err := headState.SetSlot(i); err != nil {
t.Fatal(err)
}
svc.headFetcher = &mock.ChainService{
State: headState,
}
if helpers.IsEpochEnd(i) {
continue
}
// Send in a loop to ensure it is delivered (busy wait for the service to subscribe to the state feed).
for sent := 0; sent == 0; {
sent = svc.stateNotifier.StateFeed().Send(event)
}
}
if err := svc.Stop(); err != nil {
t.Fatal(err)
}
exitRoutine <- true
// The context should have been canceled.
if svc.ctx.Err() != context.Canceled {
t.Error("context was not canceled")
}
testutil.AssertLogsContain(t, hook, "Received block processed event")
// Even though there was a skip slot, we should still be able to archive
// upon the next block event afterwards.
testutil.AssertLogsContain(t, hook, "Successfully archived")
}
func TestArchiverService_ComputesAndSavesParticipation(t *testing.T) {
hook := logTest.NewGlobal()
validatorCount := uint64(100)
headState, err := setupState(validatorCount)
if err != nil {
t.Fatal(err)
}
svc, beaconDB := setupService(t)
defer dbutil.TeardownDB(t, beaconDB)
svc.headFetcher = &mock.ChainService{
State: headState,
}
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
triggerStateEvent(t, svc, event)
attestedBalance := uint64(1)
currentEpoch := helpers.CurrentEpoch(headState)
wanted := &ethpb.ValidatorParticipation{
VotedEther: attestedBalance,
EligibleEther: validatorCount * params.BeaconConfig().MaxEffectiveBalance,
GlobalParticipationRate: float32(attestedBalance) / float32(validatorCount*params.BeaconConfig().MaxEffectiveBalance),
}
retrieved, err := svc.beaconDB.ArchivedValidatorParticipation(svc.ctx, currentEpoch)
if err != nil {
t.Fatal(err)
}
if !proto.Equal(wanted, retrieved) {
t.Errorf("Wanted participation for epoch %d %v, retrieved %v", currentEpoch-1, wanted, retrieved)
}
testutil.AssertLogsContain(t, hook, "Successfully archived")
}
func TestArchiverService_SavesIndicesAndBalances(t *testing.T) {
hook := logTest.NewGlobal()
validatorCount := uint64(100)
headState, err := setupState(validatorCount)
if err != nil {
t.Fatal(err)
}
svc, beaconDB := setupService(t)
defer dbutil.TeardownDB(t, beaconDB)
svc.headFetcher = &mock.ChainService{
State: headState,
}
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
triggerStateEvent(t, svc, event)
retrieved, err := svc.beaconDB.ArchivedBalances(svc.ctx, helpers.CurrentEpoch(headState))
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(headState.Balances(), retrieved) {
t.Errorf(
"Wanted balances for epoch %d %v, retrieved %v",
helpers.CurrentEpoch(headState),
headState.Balances(),
retrieved,
)
}
testutil.AssertLogsContain(t, hook, "Successfully archived")
}
func TestArchiverService_SavesCommitteeInfo(t *testing.T) {
hook := logTest.NewGlobal()
validatorCount := uint64(100)
headState, err := setupState(validatorCount)
if err != nil {
t.Fatal(err)
}
svc, beaconDB := setupService(t)
defer dbutil.TeardownDB(t, beaconDB)
svc.headFetcher = &mock.ChainService{
State: headState,
}
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
triggerStateEvent(t, svc, event)
currentEpoch := helpers.CurrentEpoch(headState)
proposerSeed, err := helpers.Seed(headState, currentEpoch, params.BeaconConfig().DomainBeaconProposer)
if err != nil {
t.Fatal(err)
}
attesterSeed, err := helpers.Seed(headState, currentEpoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
t.Fatal(err)
}
wanted := &pb.ArchivedCommitteeInfo{
ProposerSeed: proposerSeed[:],
AttesterSeed: attesterSeed[:],
}
retrieved, err := svc.beaconDB.ArchivedCommitteeInfo(svc.ctx, helpers.CurrentEpoch(headState))
if err != nil {
t.Fatal(err)
}
if !proto.Equal(wanted, retrieved) {
t.Errorf(
"Wanted committee info for epoch %d %v, retrieved %v",
helpers.CurrentEpoch(headState),
wanted,
retrieved,
)
}
testutil.AssertLogsContain(t, hook, "Successfully archived")
}
func TestArchiverService_SavesActivatedValidatorChanges(t *testing.T) {
hook := logTest.NewGlobal()
validatorCount := uint64(100)
headState, err := setupState(validatorCount)
if err != nil {
t.Fatal(err)
}
svc, beaconDB := setupService(t)
defer dbutil.TeardownDB(t, beaconDB)
svc.headFetcher = &mock.ChainService{
State: headState,
}
prevEpoch := helpers.PrevEpoch(headState)
delayedActEpoch := helpers.ActivationExitEpoch(prevEpoch)
val1, err := headState.ValidatorAtIndex(4)
if err != nil {
t.Fatal(err)
}
val1.ActivationEpoch = delayedActEpoch
val2, err := headState.ValidatorAtIndex(5)
if err != nil {
t.Fatal(err)
}
val2.ActivationEpoch = delayedActEpoch
if err := headState.UpdateValidatorAtIndex(4, val1); err != nil {
t.Fatal(err)
}
if err := headState.UpdateValidatorAtIndex(5, val1); err != nil {
t.Fatal(err)
}
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
triggerStateEvent(t, svc, event)
retrieved, err := beaconDB.ArchivedActiveValidatorChanges(svc.ctx, prevEpoch)
if err != nil {
t.Fatal(err)
}
if retrieved == nil {
t.Fatal("Retrieved indices are nil")
}
if len(retrieved.Activated) != 98 {
t.Error("Did not get wanted active length")
}
testutil.AssertLogsContain(t, hook, "Successfully archived")
}
func TestArchiverService_SavesSlashedValidatorChanges(t *testing.T) {
hook := logTest.NewGlobal()
validatorCount := uint64(100)
headState, err := setupState(validatorCount)
if err != nil {
t.Fatal(err)
}
svc, beaconDB := setupService(t)
defer dbutil.TeardownDB(t, beaconDB)
svc.headFetcher = &mock.ChainService{
State: headState,
}
prevEpoch := helpers.PrevEpoch(headState)
val1, err := headState.ValidatorAtIndex(95)
if err != nil {
t.Fatal(err)
}
val1.Slashed = true
val2, err := headState.ValidatorAtIndex(96)
if err != nil {
t.Fatal(err)
}
val2.Slashed = true
if err := headState.UpdateValidatorAtIndex(95, val1); err != nil {
t.Fatal(err)
}
if err := headState.UpdateValidatorAtIndex(96, val1); err != nil {
t.Fatal(err)
}
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
triggerStateEvent(t, svc, event)
retrieved, err := beaconDB.ArchivedActiveValidatorChanges(svc.ctx, prevEpoch)
if err != nil {
t.Fatal(err)
}
if retrieved == nil {
t.Fatal("Retrieved indices are nil")
}
if !reflect.DeepEqual(retrieved.Slashed, []uint64{95, 96}) {
t.Errorf("Wanted indices 95, 96 slashed, received %v", retrieved.Slashed)
}
testutil.AssertLogsContain(t, hook, "Successfully archived")
}
func TestArchiverService_SavesExitedValidatorChanges(t *testing.T) {
hook := logTest.NewGlobal()
validatorCount := uint64(100)
headState, err := setupState(validatorCount)
if err != nil {
t.Fatal(err)
}
svc, beaconDB := setupService(t)
defer dbutil.TeardownDB(t, beaconDB)
svc.headFetcher = &mock.ChainService{
State: headState,
}
prevEpoch := helpers.PrevEpoch(headState)
val, err := headState.ValidatorAtIndex(95)
if err != nil {
t.Fatal(err)
}
val.ExitEpoch = prevEpoch
val.WithdrawableEpoch = prevEpoch + params.BeaconConfig().MinValidatorWithdrawabilityDelay
if err := headState.UpdateValidatorAtIndex(95, val); err != nil {
t.Fatal(err)
}
event := &feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
BlockRoot: [32]byte{1, 2, 3},
Verified: true,
},
}
triggerStateEvent(t, svc, event)
testutil.AssertLogsContain(t, hook, "Successfully archived")
retrieved, err := beaconDB.ArchivedActiveValidatorChanges(svc.ctx, prevEpoch)
if err != nil {
t.Fatal(err)
}
if retrieved == nil {
t.Fatal("Retrieved indices are nil")
}
if !reflect.DeepEqual(retrieved.Exited, []uint64{95}) {
t.Errorf("Wanted indices 95 exited, received %v", retrieved.Exited)
}
}
func setupState(validatorCount uint64) (*stateTrie.BeaconState, error) {
validators := make([]*ethpb.Validator, validatorCount)
balances := make([]uint64, validatorCount)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
WithdrawableEpoch: params.BeaconConfig().FarFutureEpoch,
EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance,
}
balances[i] = params.BeaconConfig().MaxEffectiveBalance
}
atts := []*pb.PendingAttestation{{Data: &ethpb.AttestationData{Target: &ethpb.Checkpoint{}}}}
// We initialize a head state that has attestations from participated
// validators in a simulated fashion.
st := testutil.NewBeaconState()
if err := st.SetSlot((2 * params.BeaconConfig().SlotsPerEpoch) - 1); err != nil {
return nil, err
}
if err := st.SetValidators(validators); err != nil {
return nil, err
}
if err := st.SetBalances(balances); err != nil {
return nil, err
}
if err := st.SetCurrentEpochAttestations(atts); err != nil {
return nil, err
}
return st, nil
}
func setupService(t *testing.T) (*Service, db.Database) {
beaconDB := dbutil.SetupDB(t)
ctx, cancel := context.WithCancel(context.Background())
validatorCount := uint64(100)
totalBalance := validatorCount * params.BeaconConfig().MaxEffectiveBalance
mockChainService := &mock.ChainService{}
return &Service{
beaconDB: beaconDB,
ctx: ctx,
cancel: cancel,
stateNotifier: mockChainService.StateNotifier(),
participationFetcher: &mock.ChainService{
Balance: &precompute.Balance{PrevEpoch: totalBalance, PrevEpochTargetAttesters: 1}},
}, beaconDB
}
func triggerStateEvent(t *testing.T, svc *Service, event *feed.Event) {
exitRoutine := make(chan bool)
go func() {
svc.run(svc.ctx)
<-exitRoutine
}()
// Send in a loop to ensure it is delivered (busy wait for the service to subscribe to the state feed).
for sent := 0; sent == 0; {
sent = svc.stateNotifier.StateFeed().Send(event)
}
if err := svc.Stop(); err != nil {
t.Fatal(err)
}
exitRoutine <- true
// The context should have been canceled.
if svc.ctx.Err() != context.Canceled {
t.Error("context was not canceled")
}
}

View File

@@ -1,4 +1,5 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
load("@prysm//tools/go:def.bzl", "go_library")
load("@io_bazel_rules_go//go:def.bzl", "go_test")
go_library(
name = "go_default_library",
@@ -29,7 +30,6 @@ go_library(
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/core/state:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/db/filters:go_default_library",
"//beacon-chain/flags:go_default_library",
"//beacon-chain/forkchoice:go_default_library",
"//beacon-chain/forkchoice/protoarray:go_default_library",
@@ -43,6 +43,7 @@ go_library(
"//beacon-chain/state/stateutil:go_default_library",
"//proto/beacon/p2p/v1:go_default_library",
"//shared/attestationutil:go_default_library",
"//shared/bls:go_default_library",
"//shared/bytesutil:go_default_library",
"//shared/featureconfig:go_default_library",
"//shared/params:go_default_library",
@@ -54,7 +55,6 @@ go_library(
"@com_github_prometheus_client_golang//prometheus:go_default_library",
"@com_github_prometheus_client_golang//prometheus/promauto:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_prysmaticlabs_go_ssz//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@io_opencensus_go//trace:go_default_library",
],
@@ -74,14 +74,16 @@ go_test(
srcs = [
"chain_info_test.go",
"head_test.go",
"init_sync_process_block_test.go",
"info_test.go",
"process_attestation_test.go",
"process_block_test.go",
"receive_attestation_test.go",
"receive_block_test.go",
"service_test.go",
],
embed = [":go_default_library"],
deps = [
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/cache/depositcache:go_default_library",
"//beacon-chain/core/blocks:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
@@ -97,6 +99,8 @@ go_test(
"//shared/event:go_default_library",
"//shared/params:go_default_library",
"//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"@com_github_ethereum_go_ethereum//:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_ethereum_go_ethereum//core/types:go_default_library",
@@ -114,6 +118,7 @@ go_test(
name = "go_raceon_test",
srcs = [
"chain_info_norace_test.go",
"receive_block_test.go",
"service_norace_test.go",
],
embed = [":go_default_library"],
@@ -127,6 +132,7 @@ go_test(
race = "on",
tags = ["race_on"],
deps = [
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/cache/depositcache:go_default_library",
"//beacon-chain/core/blocks:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
@@ -140,6 +146,8 @@ go_test(
"//shared/event:go_default_library",
"//shared/params:go_default_library",
"//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"@com_github_ethereum_go_ethereum//:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_ethereum_go_ethereum//core/types:go_default_library",

View File

@@ -1,18 +1,18 @@
package blockchain
import (
"bytes"
"context"
"time"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"go.opencensus.io/trace"
)
// ChainInfoFetcher defines a common interface for methods in blockchain service which
@@ -21,6 +21,7 @@ type ChainInfoFetcher interface {
HeadFetcher
FinalizationFetcher
GenesisFetcher
CanonicalFetcher
}
// TimeFetcher retrieves the Eth2 data that's related to time.
@@ -41,8 +42,11 @@ type HeadFetcher interface {
HeadRoot(ctx context.Context) ([]byte, error)
HeadBlock(ctx context.Context) (*ethpb.SignedBeaconBlock, error)
HeadState(ctx context.Context) (*state.BeaconState, error)
HeadValidatorsIndices(epoch uint64) ([]uint64, error)
HeadSeed(epoch uint64) ([32]byte, error)
HeadValidatorsIndices(ctx context.Context, epoch uint64) ([]uint64, error)
HeadSeed(ctx context.Context, epoch uint64) ([32]byte, error)
HeadGenesisValidatorRoot() [32]byte
HeadETH1Data() *ethpb.Eth1Data
ProtoArrayStore() *protoarray.Store
}
// ForkFetcher retrieves the current fork information of the Ethereum beacon chain.
@@ -50,6 +54,12 @@ type ForkFetcher interface {
CurrentFork() *pb.Fork
}
// CanonicalFetcher retrieves the current chain's canonical information.
type CanonicalFetcher interface {
IsCanonical(ctx context.Context, blockRoot [32]byte) (bool, error)
VerifyBlkDescendant(ctx context.Context, blockRoot [32]byte) error
}
// FinalizationFetcher defines a common interface for methods in blockchain service which
// directly retrieves finalization and justification related data.
type FinalizationFetcher interface {
@@ -58,24 +68,12 @@ type FinalizationFetcher interface {
PreviousJustifiedCheckpt() *ethpb.Checkpoint
}
// ParticipationFetcher defines a common interface for methods in blockchain service which
// directly retrieves validator participation related data.
type ParticipationFetcher interface {
Participation(epoch uint64) *precompute.Balance
}
// FinalizedCheckpt returns the latest finalized checkpoint from head state.
func (s *Service) FinalizedCheckpt() *ethpb.Checkpoint {
if s.finalizedCheckpt == nil {
return &ethpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}
}
// If head state exists but there hasn't been a finalized check point,
// the check point's root should refer to genesis block root.
if bytes.Equal(s.finalizedCheckpt.Root, params.BeaconConfig().ZeroHash[:]) {
return &ethpb.Checkpoint{Root: s.genesisRoot[:]}
}
return state.CopyCheckpoint(s.finalizedCheckpt)
}
@@ -85,12 +83,6 @@ func (s *Service) CurrentJustifiedCheckpt() *ethpb.Checkpoint {
return &ethpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}
}
// If head state exists but there hasn't been a justified check point,
// the check point root should refer to genesis block root.
if bytes.Equal(s.justifiedCheckpt.Root, params.BeaconConfig().ZeroHash[:]) {
return &ethpb.Checkpoint{Root: s.genesisRoot[:]}
}
return state.CopyCheckpoint(s.justifiedCheckpt)
}
@@ -100,12 +92,6 @@ func (s *Service) PreviousJustifiedCheckpt() *ethpb.Checkpoint {
return &ethpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}
}
// If head state exists but there hasn't been a justified check point,
// the check point root should refer to genesis block root.
if bytes.Equal(s.prevJustifiedCheckpt.Root, params.BeaconConfig().ZeroHash[:]) {
return &ethpb.Checkpoint{Root: s.genesisRoot[:]}
}
return state.CopyCheckpoint(s.prevJustifiedCheckpt)
}
@@ -133,7 +119,7 @@ func (s *Service) HeadRoot(ctx context.Context) ([]byte, error) {
return params.BeaconConfig().ZeroHash[:], nil
}
r, err := ssz.HashTreeRoot(b.Block)
r, err := stateutil.BlockRoot(b.Block)
if err != nil {
return nil, err
}
@@ -142,7 +128,7 @@ func (s *Service) HeadRoot(ctx context.Context) ([]byte, error) {
}
// HeadBlock returns the head block of the chain.
// If the head state is nil from service struct,
// If the head is nil from service struct,
// it will attempt to get the head block from DB.
func (s *Service) HeadBlock(ctx context.Context) (*ethpb.SignedBeaconBlock, error) {
if s.hasHeadState() {
@@ -153,31 +139,59 @@ func (s *Service) HeadBlock(ctx context.Context) (*ethpb.SignedBeaconBlock, erro
}
// HeadState returns the head state of the chain.
// If the head state is nil from service struct,
// If the head is nil from service struct,
// it will attempt to get the head state from DB.
func (s *Service) HeadState(ctx context.Context) (*state.BeaconState, error) {
if s.hasHeadState() {
return s.headState(), nil
ctx, span := trace.StartSpan(ctx, "blockChain.HeadState")
defer span.End()
ok := s.hasHeadState()
span.AddAttributes(trace.BoolAttribute("cache_hit", ok))
if ok {
return s.headState(ctx), nil
}
return s.beaconDB.HeadState(ctx)
}
// HeadValidatorsIndices returns a list of active validator indices from the head view of a given epoch.
func (s *Service) HeadValidatorsIndices(epoch uint64) ([]uint64, error) {
func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch uint64) ([]uint64, error) {
if !s.hasHeadState() {
return []uint64{}, nil
}
return helpers.ActiveValidatorIndices(s.headState(), epoch)
return helpers.ActiveValidatorIndices(s.headState(ctx), epoch)
}
// HeadSeed returns the seed from the head view of a given epoch.
func (s *Service) HeadSeed(epoch uint64) ([32]byte, error) {
func (s *Service) HeadSeed(ctx context.Context, epoch uint64) ([32]byte, error) {
if !s.hasHeadState() {
return [32]byte{}, nil
}
return helpers.Seed(s.headState(), epoch, params.BeaconConfig().DomainBeaconAttester)
return helpers.Seed(s.headState(ctx), epoch, params.BeaconConfig().DomainBeaconAttester)
}
// HeadGenesisValidatorRoot returns genesis validator root of the head state.
func (s *Service) HeadGenesisValidatorRoot() [32]byte {
if !s.hasHeadState() {
return [32]byte{}
}
return s.headGenesisValidatorRoot()
}
// HeadETH1Data returns the eth1data of the current head state.
func (s *Service) HeadETH1Data() *ethpb.Eth1Data {
if !s.hasHeadState() {
return &ethpb.Eth1Data{}
}
return s.head.state.Eth1Data()
}
// ProtoArrayStore returns the proto array store object.
func (s *Service) ProtoArrayStore() *protoarray.Store {
return s.forkChoiceStore.Store()
}
// GenesisTime returns the genesis time of beacon chain.
@@ -205,10 +219,16 @@ func (s *Service) CurrentFork() *pb.Fork {
return s.head.state.Fork()
}
// Participation returns the participation stats of a given epoch.
func (s *Service) Participation(epoch uint64) *precompute.Balance {
s.epochParticipationLock.RLock()
defer s.epochParticipationLock.RUnlock()
// IsCanonical returns true if the input block root is part of the canonical chain.
func (s *Service) IsCanonical(ctx context.Context, blockRoot [32]byte) (bool, error) {
// If the block has been finalized, the block will always be part of the canonical chain.
if s.beaconDB.IsFinalizedBlock(ctx, blockRoot) {
return true, nil
}
return s.epochParticipation[epoch]
// If the block has not been finalized, the block must be recent. Check recent canonical roots
// mapping which uses proto array fork choice.
s.recentCanonicalBlocksLock.RLock()
defer s.recentCanonicalBlocksLock.RUnlock()
return s.recentCanonicalBlocks[blockRoot], nil
}

View File

@@ -5,74 +5,59 @@ import (
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestHeadSlot_DataRace(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
s := &Service{
beaconDB: db,
}
go func() {
if err := s.saveHead(context.Background(), [32]byte{}, ); err != nil {
t.Fatal(err)
}
require.NoError(t, s.saveHead(context.Background(), [32]byte{}))
}()
s.HeadSlot()
}
func TestHeadRoot_DataRace(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
s := &Service{
beaconDB: db,
head: &head{root: [32]byte{'A'}},
stateGen: stategen.New(db, cache.NewStateSummaryCache()),
stateGen: stategen.New(db, sc),
}
go func() {
if err := s.saveHead(context.Background(), [32]byte{}, ); err != nil {
t.Fatal(err)
}
require.NoError(t, s.saveHead(context.Background(), [32]byte{}))
}()
if _, err := s.HeadRoot(context.Background()); err != nil {
t.Fatal(err)
}
_, err := s.HeadRoot(context.Background())
require.NoError(t, err)
}
func TestHeadBlock_DataRace(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
s := &Service{
beaconDB: db,
head: &head{block: &ethpb.SignedBeaconBlock{}},
stateGen: stategen.New(db, cache.NewStateSummaryCache()),
stateGen: stategen.New(db, sc),
}
go func() {
if err := s.saveHead(context.Background(), [32]byte{}, ); err != nil {
t.Fatal(err)
}
require.NoError(t, s.saveHead(context.Background(), [32]byte{}))
}()
if _, err := s.HeadBlock(context.Background()); err != nil {
t.Fatal(err)
}
_, err := s.HeadBlock(context.Background())
require.NoError(t, err)
}
func TestHeadState_DataRace(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
s := &Service{
beaconDB: db,
stateGen: stategen.New(db, cache.NewStateSummaryCache()),
stateGen: stategen.New(db, sc),
}
go func() {
if err := s.saveHead(context.Background(), [32]byte{}, ); err != nil {
t.Fatal(err)
}
require.NoError(t, s.saveHead(context.Background(), [32]byte{}))
}()
if _, err := s.HeadState(context.Background()); err != nil {
t.Fatal(err)
}
_, err := s.HeadState(context.Background())
require.NoError(t, err)
}

View File

@@ -3,7 +3,6 @@ package blockchain
import (
"bytes"
"context"
"reflect"
"testing"
"time"
@@ -13,6 +12,8 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
// Ensure Service implements chain info interface.
@@ -21,47 +22,39 @@ var _ = TimeFetcher(&Service{})
var _ = ForkFetcher(&Service{})
func TestFinalizedCheckpt_Nil(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
c := setupBeaconChain(t, db)
db, sc := testDB.SetupDB(t)
c := setupBeaconChain(t, db, sc)
if !bytes.Equal(c.FinalizedCheckpt().Root, params.BeaconConfig().ZeroHash[:]) {
t.Error("Incorrect pre chain start value")
}
}
func TestHeadRoot_Nil(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
c := setupBeaconChain(t, db)
db, sc := testDB.SetupDB(t)
c := setupBeaconChain(t, db, sc)
headRoot, err := c.HeadRoot(context.Background())
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if !bytes.Equal(headRoot, params.BeaconConfig().ZeroHash[:]) {
t.Error("Incorrect pre chain start value")
}
}
func TestFinalizedCheckpt_CanRetrieve(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
cp := &ethpb.Checkpoint{Epoch: 5, Root: []byte("foo")}
c := setupBeaconChain(t, db)
c := setupBeaconChain(t, db, sc)
c.finalizedCheckpt = cp
if c.FinalizedCheckpt().Epoch != cp.Epoch {
t.Errorf("Finalized epoch at genesis should be %d, got: %d", cp.Epoch, c.FinalizedCheckpt().Epoch)
}
assert.Equal(t, cp.Epoch, c.FinalizedCheckpt().Epoch, "Unexpected finalized epoch")
}
func TestFinalizedCheckpt_GenesisRootOk(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
genesisRoot := [32]byte{'A'}
cp := &ethpb.Checkpoint{Root: genesisRoot[:]}
c := setupBeaconChain(t, db)
c := setupBeaconChain(t, db, sc)
c.finalizedCheckpt = cp
c.genesisRoot = genesisRoot
@@ -71,25 +64,21 @@ func TestFinalizedCheckpt_GenesisRootOk(t *testing.T) {
}
func TestCurrentJustifiedCheckpt_CanRetrieve(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
cp := &ethpb.Checkpoint{Epoch: 6, Root: []byte("foo")}
c := setupBeaconChain(t, db)
c := setupBeaconChain(t, db, sc)
c.justifiedCheckpt = cp
if c.CurrentJustifiedCheckpt().Epoch != cp.Epoch {
t.Errorf("Current Justifiied epoch at genesis should be %d, got: %d", cp.Epoch, c.CurrentJustifiedCheckpt().Epoch)
}
assert.Equal(t, cp.Epoch, c.CurrentJustifiedCheckpt().Epoch, "Unexpected justified epoch")
}
func TestJustifiedCheckpt_GenesisRootOk(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
genesisRoot := [32]byte{'B'}
cp := &ethpb.Checkpoint{Root: genesisRoot[:]}
c := setupBeaconChain(t, db)
c := setupBeaconChain(t, db, sc)
c.justifiedCheckpt = cp
c.genesisRoot = genesisRoot
@@ -99,25 +88,21 @@ func TestJustifiedCheckpt_GenesisRootOk(t *testing.T) {
}
func TestPreviousJustifiedCheckpt_CanRetrieve(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
cp := &ethpb.Checkpoint{Epoch: 7, Root: []byte("foo")}
c := setupBeaconChain(t, db)
c := setupBeaconChain(t, db, sc)
c.prevJustifiedCheckpt = cp
if c.PreviousJustifiedCheckpt().Epoch != cp.Epoch {
t.Errorf("Previous Justifiied epoch at genesis should be %d, got: %d", cp.Epoch, c.PreviousJustifiedCheckpt().Epoch)
}
assert.Equal(t, cp.Epoch, c.PreviousJustifiedCheckpt().Epoch, "Unexpected previous justified epoch")
}
func TestPrevJustifiedCheckpt_GenesisRootOk(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
genesisRoot := [32]byte{'C'}
cp := &ethpb.Checkpoint{Root: genesisRoot[:]}
c := setupBeaconChain(t, db)
c := setupBeaconChain(t, db, sc)
c.prevJustifiedCheckpt = cp
c.genesisRoot = genesisRoot
@@ -133,49 +118,34 @@ func TestHeadSlot_CanRetrieve(t *testing.T) {
t.Fatal(err)
}
c.head = &head{slot: 100, state: s}
if c.HeadSlot() != 100 {
t.Errorf("Wanted head slot: %d, got: %d", 100, c.HeadSlot())
}
assert.Equal(t, uint64(100), c.headSlot())
}
func TestHeadRoot_CanRetrieve(t *testing.T) {
c := &Service{}
c.head = &head{root: [32]byte{'A'}}
if [32]byte{'A'} != c.headRoot() {
t.Errorf("Wanted head root: %v, got: %d", []byte{'A'}, c.headRoot())
}
assert.Equal(t, [32]byte{'A'}, c.headRoot())
}
func TestHeadBlock_CanRetrieve(t *testing.T) {
b := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 1}}
s, err := state.InitializeFromProto(&pb.BeaconState{})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
c := &Service{}
c.head = &head{block: b, state: s}
recevied, err := c.HeadBlock(context.Background())
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(b, recevied) {
t.Error("incorrect head block received")
}
require.NoError(t, err)
assert.DeepEqual(t, b, recevied, "Incorrect head block received")
}
func TestHeadState_CanRetrieve(t *testing.T) {
s, err := state.InitializeFromProto(&pb.BeaconState{Slot: 2, GenesisValidatorsRoot: params.BeaconConfig().ZeroHash[:]})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
c := &Service{}
c.head = &head{state: s}
headState, err := c.HeadState(context.Background())
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if !proto.Equal(s.InnerStateUnsafe(), headState.InnerStateUnsafe()) {
t.Error("incorrect head state received")
}
@@ -184,20 +154,44 @@ func TestHeadState_CanRetrieve(t *testing.T) {
func TestGenesisTime_CanRetrieve(t *testing.T) {
c := &Service{genesisTime: time.Unix(999, 0)}
wanted := time.Unix(999, 0)
if c.GenesisTime() != wanted {
t.Error("Did not get wanted genesis time")
}
assert.Equal(t, wanted, c.GenesisTime(), "Did not get wanted genesis time")
}
func TestCurrentFork_CanRetrieve(t *testing.T) {
f := &pb.Fork{Epoch: 999}
s, err := state.InitializeFromProto(&pb.BeaconState{Fork: f})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
c := &Service{}
c.head = &head{state: s}
if !proto.Equal(c.CurrentFork(), f) {
t.Error("Received incorrect fork version")
}
}
func TestGenesisValidatorRoot_CanRetrieve(t *testing.T) {
// Should not panic if head state is nil.
c := &Service{}
assert.Equal(t, [32]byte{}, c.GenesisValidatorRoot(), "Did not get correct genesis validator root")
s, err := state.InitializeFromProto(&pb.BeaconState{GenesisValidatorsRoot: []byte{'a'}})
require.NoError(t, err)
c.head = &head{state: s}
assert.Equal(t, [32]byte{'a'}, c.GenesisValidatorRoot(), "Did not get correct genesis validator root")
}
func TestHeadETH1Data_Nil(t *testing.T) {
db, sc := testDB.SetupDB(t)
c := setupBeaconChain(t, db, sc)
assert.DeepEqual(t, &ethpb.Eth1Data{}, c.HeadETH1Data(), "Incorrect pre chain start value")
}
func TestHeadETH1Data_CanRetrieve(t *testing.T) {
d := &ethpb.Eth1Data{DepositCount: 999}
s, err := state.InitializeFromProto(&pb.BeaconState{Eth1Data: d})
require.NoError(t, err)
c := &Service{}
c.head = &head{state: s}
if !proto.Equal(c.HeadETH1Data(), d) {
t.Error("Received incorrect eth1 data")
}
}

View File

@@ -1,15 +1,21 @@
package blockchain
import (
"bytes"
"context"
"fmt"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
@@ -21,10 +27,10 @@ type head struct {
state *state.BeaconState // current head state.
}
// This gets head from the fork choice service and saves head related items
// (ie root, block, state) to the local service cache.
// Determined the head from the fork choice service and saves its new data
// (head root, head block, and head state) to the local service cache.
func (s *Service) updateHead(ctx context.Context, balances []uint64) error {
ctx, span := trace.StartSpan(ctx, "blockchain.updateHead")
ctx, span := trace.StartSpan(ctx, "blockChain.updateHead")
defer span.End()
// To get the proper head update, a node first checks its best justified
@@ -32,16 +38,29 @@ func (s *Service) updateHead(ctx context.Context, balances []uint64) error {
// ensure head gets its best justified info.
if s.bestJustifiedCheckpt.Epoch > s.justifiedCheckpt.Epoch {
s.justifiedCheckpt = s.bestJustifiedCheckpt
if err := s.cacheJustifiedStateBalances(ctx, bytesutil.ToBytes32(s.justifiedCheckpt.Root)); err != nil {
return err
}
}
// Get head from the fork choice service.
f := s.finalizedCheckpt
j := s.justifiedCheckpt
headRoot, err := s.forkChoiceStore.Head(ctx, j.Epoch, bytesutil.ToBytes32(j.Root), balances, f.Epoch)
// To get head before the first justified epoch, the fork choice will start with genesis root
// instead of zero hashes.
headStartRoot := bytesutil.ToBytes32(j.Root)
if headStartRoot == params.BeaconConfig().ZeroHash {
headStartRoot = s.genesisRoot
}
headRoot, err := s.forkChoiceStore.Head(ctx, j.Epoch, headStartRoot, balances, f.Epoch)
if err != nil {
return err
}
if err := s.updateRecentCanonicalBlocks(ctx, headRoot); err != nil {
return err
}
// Save head to the local service cache.
return s.saveHead(ctx, headRoot)
}
@@ -49,7 +68,7 @@ func (s *Service) updateHead(ctx context.Context, balances []uint64) error {
// This saves head info to the local service cache, it also saves the
// new head root to the DB.
func (s *Service) saveHead(ctx context.Context, headRoot [32]byte) error {
ctx, span := trace.StartSpan(ctx, "blockchain.saveHead")
ctx, span := trace.StartSpan(ctx, "blockChain.saveHead")
defer span.End()
// Do nothing if head hasn't changed.
@@ -59,15 +78,8 @@ func (s *Service) saveHead(ctx context.Context, headRoot [32]byte) error {
// If the head state is not available, just return nil.
// There's nothing to cache
if !featureconfig.Get().DisableNewStateMgmt {
if !s.stateGen.StateSummaryExists(ctx, headRoot) {
return nil
}
} else {
_, cached := s.initSyncState[headRoot]
if !cached && !s.beaconDB.HasState(ctx, headRoot) {
return nil
}
if !s.stateGen.StateSummaryExists(ctx, headRoot) {
return nil
}
// Get the new head block from DB.
@@ -80,26 +92,31 @@ func (s *Service) saveHead(ctx context.Context, headRoot [32]byte) error {
}
// Get the new head state from cached state or DB.
var newHeadState *state.BeaconState
if !featureconfig.Get().DisableNewStateMgmt {
newHeadState, err = s.stateGen.StateByRoot(ctx, headRoot)
if err != nil {
return errors.Wrap(err, "could not retrieve head state in DB")
}
} else {
var exists bool
newHeadState, exists = s.initSyncState[headRoot]
if !exists {
newHeadState, err = s.beaconDB.State(ctx, headRoot)
if err != nil {
return errors.Wrap(err, "could not retrieve head state in DB")
}
}
newHeadState, err := s.stateGen.StateByRoot(ctx, headRoot)
if err != nil {
return errors.Wrap(err, "could not retrieve head state in DB")
}
if newHeadState == nil {
return errors.New("cannot save nil head state")
}
// A chain re-org occurred, so we fire an event notifying the rest of the services.
if bytesutil.ToBytes32(newHeadBlock.Block.ParentRoot) != s.headRoot() {
log.WithFields(logrus.Fields{
"newSlot": fmt.Sprintf("%d", newHeadBlock.Block.Slot),
"oldSlot": fmt.Sprintf("%d", s.headSlot()),
}).Debug("Chain reorg occurred")
s.stateNotifier.StateFeed().Send(&feed.Event{
Type: statefeed.Reorg,
Data: &statefeed.ReorgData{
NewSlot: newHeadBlock.Block.Slot,
OldSlot: s.headSlot(),
},
})
reorgCount.Inc()
}
// Cache the new head info.
s.setHead(headRoot, newHeadBlock, newHeadState)
@@ -112,40 +129,22 @@ func (s *Service) saveHead(ctx context.Context, headRoot [32]byte) error {
}
// This gets called to update canonical root mapping. It does not save head block
// root in DB. With the inception of inital-sync-cache-state flag, it uses finalized
// root in DB. With the inception of initial-sync-cache-state flag, it uses finalized
// check point as anchors to resume sync therefore head is no longer needed to be saved on per slot basis.
func (s *Service) saveHeadNoDB(ctx context.Context, b *ethpb.SignedBeaconBlock, r [32]byte) error {
func (s *Service) saveHeadNoDB(ctx context.Context, b *ethpb.SignedBeaconBlock, r [32]byte, hs *state.BeaconState) error {
cachedHeadRoot, err := s.HeadRoot(ctx)
if err != nil {
return errors.Wrap(err, "could not get head root from cache")
}
if bytes.Equal(r[:], cachedHeadRoot) {
return nil
}
if b == nil || b.Block == nil {
return errors.New("cannot save nil head block")
}
var headState *state.BeaconState
var err error
if !featureconfig.Get().DisableNewStateMgmt {
headState, err = s.stateGen.StateByRoot(ctx, r)
if err != nil {
return errors.Wrap(err, "could not retrieve head state in DB")
}
} else {
headState, err = s.beaconDB.State(ctx, r)
if err != nil {
return errors.Wrap(err, "could not retrieve head state in DB")
}
if headState == nil {
s.initSyncStateLock.RLock()
cachedHeadState, ok := s.initSyncState[r]
if ok {
headState = cachedHeadState
}
s.initSyncStateLock.RUnlock()
}
}
if headState == nil {
return errors.New("nil head state")
}
s.setHead(r, stateTrie.CopySignedBeaconBlock(b), headState)
s.setHeadInitialSync(r, stateTrie.CopySignedBeaconBlock(b), hs)
return nil
}
@@ -163,6 +162,22 @@ func (s *Service) setHead(root [32]byte, block *ethpb.SignedBeaconBlock, state *
}
}
// This sets head view object which is used to track the head slot, root, block and state. The method
// assumes that state being passed into the method will not be modified by any other alternate
// caller which holds the state's reference.
func (s *Service) setHeadInitialSync(root [32]byte, block *ethpb.SignedBeaconBlock, state *state.BeaconState) {
s.headLock.Lock()
defer s.headLock.Unlock()
// This does a full copy of the block only.
s.head = &head{
slot: block.Block.Slot,
root: root,
block: stateTrie.CopySignedBeaconBlock(block),
state: state,
}
}
// This returns the head slot.
func (s *Service) headSlot() uint64 {
s.headLock.RLock()
@@ -195,13 +210,24 @@ func (s *Service) headBlock() *ethpb.SignedBeaconBlock {
// This returns the head state.
// It does a full copy on head state for immutability.
func (s *Service) headState() *state.BeaconState {
func (s *Service) headState(ctx context.Context) *stateTrie.BeaconState {
ctx, span := trace.StartSpan(ctx, "blockChain.headState")
defer span.End()
s.headLock.RLock()
defer s.headLock.RUnlock()
return s.head.state.Copy()
}
// This returns the genesis validator root of the head state.
func (s *Service) headGenesisValidatorRoot() [32]byte {
s.headLock.RLock()
defer s.headLock.RUnlock()
return bytesutil.ToBytes32(s.head.state.GenesisValidatorRoot())
}
// Returns true if head state exists.
func (s *Service) hasHeadState() bool {
s.headLock.RLock()
@@ -209,3 +235,82 @@ func (s *Service) hasHeadState() bool {
return s.head != nil && s.head.state != nil
}
// This updates recent canonical block mapping. It uses input head root and retrieves
// all the canonical block roots that are ancestor of the input head block root.
func (s *Service) updateRecentCanonicalBlocks(ctx context.Context, headRoot [32]byte) error {
ctx, span := trace.StartSpan(ctx, "blockChain.updateRecentCanonicalBlocks")
defer span.End()
s.recentCanonicalBlocksLock.Lock()
defer s.recentCanonicalBlocksLock.Unlock()
s.recentCanonicalBlocks = make(map[[32]byte]bool)
s.recentCanonicalBlocks[headRoot] = true
nodes := s.forkChoiceStore.Nodes()
node := s.forkChoiceStore.Node(headRoot)
if node == nil {
return nil
}
for node.Parent != protoarray.NonExistentNode {
if ctx.Err() != nil {
return ctx.Err()
}
node = nodes[node.Parent]
s.recentCanonicalBlocks[node.Root] = true
}
return nil
}
// This caches justified state balances to be used for fork choice.
func (s *Service) cacheJustifiedStateBalances(ctx context.Context, justifiedRoot [32]byte) error {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return err
}
s.clearInitSyncBlocks()
var justifiedState *stateTrie.BeaconState
var err error
if justifiedRoot == s.genesisRoot {
justifiedState, err = s.beaconDB.GenesisState(ctx)
if err != nil {
return err
}
} else {
justifiedState, err = s.stateGen.StateByRoot(ctx, justifiedRoot)
if err != nil {
return err
}
}
if justifiedState == nil {
return errors.New("justified state can't be nil")
}
epoch := helpers.CurrentEpoch(justifiedState)
justifiedBalances := make([]uint64, justifiedState.NumValidators())
if err := justifiedState.ReadFromEveryValidator(func(idx int, val *stateTrie.ReadOnlyValidator) error {
if helpers.IsActiveValidatorUsingTrie(val, epoch) {
justifiedBalances[idx] = val.EffectiveBalance()
} else {
justifiedBalances[idx] = 0
}
return nil
}); err != nil {
return err
}
s.justifiedBalancesLock.Lock()
defer s.justifiedBalancesLock.Unlock()
s.justifiedBalances = justifiedBalances
return nil
}
func (s *Service) getJustifiedBalances() []uint64 {
s.justifiedBalancesLock.RLock()
defer s.justifiedBalancesLock.RUnlock()
return s.justifiedBalances
}

View File

@@ -3,41 +3,34 @@ package blockchain
import (
"bytes"
"context"
"reflect"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
logTest "github.com/sirupsen/logrus/hooks/test"
)
func TestSaveHead_Same(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
service := setupBeaconChain(t, db)
db, sc := testDB.SetupDB(t)
service := setupBeaconChain(t, db, sc)
r := [32]byte{'A'}
service.head = &head{slot: 0, root: r}
if err := service.saveHead(context.Background(), r); err != nil {
t.Fatal(err)
}
if service.headSlot() != 0 {
t.Error("Head did not stay the same")
}
if service.headRoot() != r {
t.Error("Head did not stay the same")
}
require.NoError(t, service.saveHead(context.Background(), r))
assert.Equal(t, uint64(0), service.headSlot(), "Head did not stay the same")
assert.Equal(t, r, service.headRoot(), "Head did not stay the same")
}
func TestSaveHead_Different(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
service := setupBeaconChain(t, db)
ctx := context.Background()
db, sc := testDB.SetupDB(t)
service := setupBeaconChain(t, db, sc)
oldRoot := [32]byte{'A'}
service.head = &head{slot: 0, root: oldRoot}
@@ -45,42 +38,104 @@ func TestSaveHead_Different(t *testing.T) {
newHeadBlock := &ethpb.BeaconBlock{Slot: 1}
newHeadSignedBlock := &ethpb.SignedBeaconBlock{Block: newHeadBlock}
if err := service.beaconDB.SaveBlock(context.Background(), newHeadSignedBlock); err != nil {
t.Fatal(err)
}
newRoot, err := ssz.HashTreeRoot(newHeadBlock)
if err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveBlock(context.Background(), newHeadSignedBlock))
newRoot, err := stateutil.BlockRoot(newHeadBlock)
require.NoError(t, err)
headState := testutil.NewBeaconState()
if err := headState.SetSlot(1); err != nil {
t.Fatal(err)
}
if err := service.beaconDB.SaveStateSummary(context.Background(), &pb.StateSummary{Slot: 1, Root: newRoot[:]}); err != nil {
t.Fatal(err)
}
if err := service.beaconDB.SaveState(context.Background(), headState, newRoot); err != nil {
t.Fatal(err)
}
if err := service.saveHead(context.Background(), newRoot); err != nil {
t.Fatal(err)
}
require.NoError(t, headState.SetSlot(1))
require.NoError(t, service.beaconDB.SaveStateSummary(context.Background(), &pb.StateSummary{Slot: 1, Root: newRoot[:]}))
require.NoError(t, service.beaconDB.SaveState(context.Background(), headState, newRoot))
require.NoError(t, service.saveHead(context.Background(), newRoot))
if service.HeadSlot() != 1 {
t.Error("Head did not change")
}
assert.Equal(t, uint64(1), service.HeadSlot(), "Head did not change")
cachedRoot, err := service.HeadRoot(context.Background())
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if !bytes.Equal(cachedRoot, newRoot[:]) {
t.Error("Head did not change")
}
if !reflect.DeepEqual(service.headBlock(), newHeadSignedBlock) {
t.Error("Head did not change")
}
if !reflect.DeepEqual(service.headState().CloneInnerState(), headState.CloneInnerState()) {
t.Error("Head did not change")
}
assert.DeepEqual(t, newHeadSignedBlock, service.headBlock(), "Head did not change")
assert.DeepEqual(t, headState.CloneInnerState(), service.headState(ctx).CloneInnerState(), "Head did not change")
}
func TestSaveHead_Different_Reorg(t *testing.T) {
ctx := context.Background()
hook := logTest.NewGlobal()
db, sc := testDB.SetupDB(t)
service := setupBeaconChain(t, db, sc)
oldRoot := [32]byte{'A'}
service.head = &head{slot: 0, root: oldRoot}
reorgChainParent := [32]byte{'B'}
newHeadBlock := &ethpb.BeaconBlock{
Slot: 1,
ParentRoot: reorgChainParent[:],
}
newHeadSignedBlock := &ethpb.SignedBeaconBlock{Block: newHeadBlock}
require.NoError(t, service.beaconDB.SaveBlock(context.Background(), newHeadSignedBlock))
newRoot, err := stateutil.BlockRoot(newHeadBlock)
require.NoError(t, err)
headState := testutil.NewBeaconState()
require.NoError(t, headState.SetSlot(1))
require.NoError(t, service.beaconDB.SaveStateSummary(context.Background(), &pb.StateSummary{Slot: 1, Root: newRoot[:]}))
require.NoError(t, service.beaconDB.SaveState(context.Background(), headState, newRoot))
require.NoError(t, service.saveHead(context.Background(), newRoot))
assert.Equal(t, uint64(1), service.HeadSlot(), "Head did not change")
cachedRoot, err := service.HeadRoot(context.Background())
require.NoError(t, err)
if !bytes.Equal(cachedRoot, newRoot[:]) {
t.Error("Head did not change")
}
assert.DeepEqual(t, newHeadSignedBlock, service.headBlock(), "Head did not change")
assert.DeepEqual(t, headState.CloneInnerState(), service.headState(ctx).CloneInnerState(), "Head did not change")
testutil.AssertLogsContain(t, hook, "Chain reorg occurred")
}
func TestUpdateRecentCanonicalBlocks_CanUpdateWithoutParent(t *testing.T) {
db, sc := testDB.SetupDB(t)
service := setupBeaconChain(t, db, sc)
r := [32]byte{'a'}
require.NoError(t, service.updateRecentCanonicalBlocks(context.Background(), r))
canonical, err := service.IsCanonical(context.Background(), r)
require.NoError(t, err)
assert.Equal(t, true, canonical, "Block should be canonical")
}
func TestUpdateRecentCanonicalBlocks_CanUpdateWithParent(t *testing.T) {
db, sc := testDB.SetupDB(t)
service := setupBeaconChain(t, db, sc)
oldHead := [32]byte{'a'}
require.NoError(t, service.forkChoiceStore.ProcessBlock(context.Background(), 1, oldHead, [32]byte{'g'}, [32]byte{}, 0, 0))
currentHead := [32]byte{'b'}
require.NoError(t, service.forkChoiceStore.ProcessBlock(context.Background(), 3, currentHead, oldHead, [32]byte{}, 0, 0))
forkedRoot := [32]byte{'c'}
require.NoError(t, service.forkChoiceStore.ProcessBlock(context.Background(), 2, forkedRoot, oldHead, [32]byte{}, 0, 0))
require.NoError(t, service.updateRecentCanonicalBlocks(context.Background(), currentHead))
canonical, err := service.IsCanonical(context.Background(), currentHead)
require.NoError(t, err)
assert.Equal(t, true, canonical, "Block should be canonical")
canonical, err = service.IsCanonical(context.Background(), oldHead)
require.NoError(t, err)
assert.Equal(t, true, canonical, "Block should be canonical")
canonical, err = service.IsCanonical(context.Background(), forkedRoot)
require.NoError(t, err)
assert.Equal(t, false, canonical, "Block should not be canonical")
}
func TestCacheJustifiedStateBalances_CanCache(t *testing.T) {
db, sc := testDB.SetupDB(t)
service := setupBeaconChain(t, db, sc)
state, _ := testutil.DeterministicGenesisState(t, 100)
r := [32]byte{'a'}
require.NoError(t, service.beaconDB.SaveStateSummary(context.Background(), &pb.StateSummary{Root: r[:]}))
require.NoError(t, service.beaconDB.SaveState(context.Background(), state, r))
require.NoError(t, service.cacheJustifiedStateBalances(context.Background(), r))
require.DeepEqual(t, service.getJustifiedBalances(), state.Balances(), "Incorrect justified balances")
}

View File

@@ -1,11 +1,12 @@
package blockchain
import (
"encoding/hex"
"fmt"
"net/http"
"strconv"
"github.com/emicklei/dot"
"github.com/prysmaticlabs/prysm/shared/params"
)
const template = `<html>
@@ -32,8 +33,8 @@ const template = `<html>
</html>`
// TreeHandler is a handler to serve /tree page in metrics.
func (s *Service) TreeHandler(w http.ResponseWriter, _ *http.Request) {
if s.headState() == nil {
func (s *Service) TreeHandler(w http.ResponseWriter, r *http.Request) {
if s.headState(r.Context()) == nil {
if _, err := w.Write([]byte("Unavailable during initial syncing")); err != nil {
log.WithError(err).Error("Failed to render p2p info page")
}
@@ -46,23 +47,25 @@ func (s *Service) TreeHandler(w http.ResponseWriter, _ *http.Request) {
graph.Attr("labeljust", "l")
dotNodes := make([]*dot.Node, len(nodes))
avgBalance := uint64(averageBalance(s.headState().Balances()))
avgBalance := uint64(averageBalance(s.headState(r.Context()).Balances()))
for i := len(nodes) - 1; i >= 0; i-- {
// Construct label for each node.
slot := strconv.Itoa(int(nodes[i].Slot))
weight := strconv.Itoa(int(nodes[i].Weight / 1e9)) // Convert unit Gwei to unit ETH.
votes := strconv.Itoa(int(nodes[i].Weight / 1e9 / avgBalance))
bestDescendent := strconv.Itoa(int(nodes[i].BestDescendent))
index := strconv.Itoa(int(i))
label := "slot: " + slot + "\n index: " + index + "\n bestDescendent: " + bestDescendent + "\n votes: " + votes + "\n weight: " + weight
slot := fmt.Sprintf("%d", nodes[i].Slot)
weight := fmt.Sprintf("%d", nodes[i].Weight/1e9) // Convert unit Gwei to unit ETH.
votes := fmt.Sprintf("%d", nodes[i].Weight/1e9/avgBalance)
index := fmt.Sprintf("%d", i)
g := nodes[i].Graffiti[:]
graffiti := hex.EncodeToString(g[:8])
label := "slot: " + slot + "\n votes: " + votes + "\n weight: " + weight + "\n graffiti: " + graffiti
var dotN dot.Node
if nodes[i].Parent != ^uint64(0) {
dotN = graph.Node(index).Box().Attr("label", label)
}
if nodes[i].Slot == s.headSlot() &&
nodes[i].BestDescendent == ^uint64(0) {
nodes[i].BestDescendant == ^uint64(0) &&
nodes[i].Parent != ^uint64(0) {
dotN = dotN.Attr("color", "green")
}
@@ -81,3 +84,11 @@ func (s *Service) TreeHandler(w http.ResponseWriter, _ *http.Request) {
log.WithError(err).Error("Failed to render p2p info page")
}
}
func averageBalance(balances []uint64) float64 {
total := uint64(0)
for i := 0; i < len(balances); i++ {
total += balances[i]
}
return float64(total) / float64(len(balances)) / float64(params.BeaconConfig().GweiPerEth)
}

View File

@@ -0,0 +1,46 @@
package blockchain
import (
"context"
"net/http"
"net/http/httptest"
"testing"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestService_TreeHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/tree", nil)
require.NoError(t, err)
ctx := context.Background()
db, sCache := testDB.SetupDB(t)
headState := testutil.NewBeaconState()
require.NoError(t, headState.SetBalances([]uint64{params.BeaconConfig().GweiPerEth}))
cfg := &Config{
BeaconDB: db,
ForkChoiceStore: protoarray.New(
0, // justifiedEpoch
0, // finalizedEpoch
[32]byte{'a'},
),
StateGen: stategen.New(db, sCache),
}
s, err := NewService(ctx, cfg)
require.NoError(t, s.forkChoiceStore.ProcessBlock(ctx, 0, [32]byte{'a'}, [32]byte{'g'}, [32]byte{'c'}, 0, 0))
require.NoError(t, s.forkChoiceStore.ProcessBlock(ctx, 1, [32]byte{'b'}, [32]byte{'a'}, [32]byte{'c'}, 0, 0))
s.setHead([32]byte{'a'}, testutil.NewBeaconBlock(), headState)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(s.TreeHandler)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
}

View File

@@ -1,220 +1,9 @@
package blockchain
import (
"context"
"sort"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
)
const maxCacheSize = 70
const initialSyncCacheSize = 45
const minimumCacheSize = initialSyncCacheSize / 3
func (s *Service) persistCachedStates(ctx context.Context, numOfStates int) error {
oldStates := make([]*stateTrie.BeaconState, 0, numOfStates)
// Add slots to the map and add epoch boundary states to the slice.
for _, rt := range s.boundaryRoots[:numOfStates-minimumCacheSize] {
oldStates = append(oldStates, s.initSyncState[rt])
}
err := s.beaconDB.SaveStates(ctx, oldStates, s.boundaryRoots[:numOfStates-minimumCacheSize])
if err != nil {
return err
}
for _, rt := range s.boundaryRoots[:numOfStates-minimumCacheSize] {
delete(s.initSyncState, rt)
}
s.boundaryRoots = s.boundaryRoots[numOfStates-minimumCacheSize:]
return nil
}
// filter out boundary candidates from our currently processed batch of states.
func (s *Service) filterBoundaryCandidates(ctx context.Context, root [32]byte, postState *stateTrie.BeaconState) {
// Only trigger on epoch start.
if !helpers.IsEpochStart(postState.Slot()) {
return
}
stateSlice := make([][32]byte, 0, len(s.initSyncState))
// Add epoch boundary roots to slice.
for rt := range s.initSyncState {
stateSlice = append(stateSlice, rt)
}
sort.Slice(stateSlice, func(i int, j int) bool {
return s.initSyncState[stateSlice[i]].Slot() < s.initSyncState[stateSlice[j]].Slot()
})
epochLength := params.BeaconConfig().SlotsPerEpoch
if len(s.boundaryRoots) > 0 {
// Retrieve previous boundary root.
previousBoundaryRoot := s.boundaryRoots[len(s.boundaryRoots)-1]
previousState, ok := s.initSyncState[previousBoundaryRoot]
if !ok {
// Remove the non-existent root and exit filtering.
s.boundaryRoots = s.boundaryRoots[:len(s.boundaryRoots)-1]
return
}
previousSlot := previousState.Slot()
// Round up slot number to account for skipped slots.
previousSlot = helpers.RoundUpToNearestEpoch(previousSlot)
if postState.Slot()-previousSlot >= epochLength {
targetSlot := postState.Slot()
tempRoots := s.loopThroughCandidates(stateSlice, previousBoundaryRoot, previousSlot, targetSlot)
s.boundaryRoots = append(s.boundaryRoots, tempRoots...)
}
}
s.boundaryRoots = append(s.boundaryRoots, root)
s.pruneOldStates()
s.pruneNonBoundaryStates()
}
// loop-through the provided candidate roots to filter out which would be appropriate boundary roots.
func (s *Service) loopThroughCandidates(stateSlice [][32]byte, previousBoundaryRoot [32]byte,
previousSlot uint64, targetSlot uint64) [][32]byte {
tempRoots := [][32]byte{}
epochLength := params.BeaconConfig().SlotsPerEpoch
// Loop through current states to filter for valid boundary states.
for i := len(stateSlice) - 1; stateSlice[i] != previousBoundaryRoot && i >= 0; i-- {
currentSlot := s.initSyncState[stateSlice[i]].Slot()
// Skip if the current slot is larger than the previous epoch
// boundary.
if currentSlot > targetSlot-epochLength {
continue
}
tempRoots = append(tempRoots, stateSlice[i])
// Switch target slot if the current slot is greater than
// 1 epoch boundary from the previously saved boundary slot.
if currentSlot > previousSlot+epochLength {
currentSlot = helpers.RoundUpToNearestEpoch(currentSlot)
targetSlot = currentSlot
continue
}
break
}
// Reverse to append the roots in ascending order corresponding
// to the respective slots.
tempRoots = bytesutil.ReverseBytes32Slice(tempRoots)
return tempRoots
}
// prune for states past the current finalized checkpoint.
func (s *Service) pruneOldStates() {
prunedBoundaryRoots := [][32]byte{}
for _, rt := range s.boundaryRoots {
st, ok := s.initSyncState[rt]
// Skip non-existent roots.
if !ok {
continue
}
if st.Slot() < helpers.StartSlot(s.FinalizedCheckpt().Epoch) {
delete(s.initSyncState, rt)
continue
}
prunedBoundaryRoots = append(prunedBoundaryRoots, rt)
}
s.boundaryRoots = prunedBoundaryRoots
}
// prune cache for non-boundary states.
func (s *Service) pruneNonBoundaryStates() {
boundaryMap := make(map[[32]byte]bool)
for i := range s.boundaryRoots {
boundaryMap[s.boundaryRoots[i]] = true
}
for rt := range s.initSyncState {
if !boundaryMap[rt] {
delete(s.initSyncState, rt)
}
}
}
func (s *Service) pruneOldNonFinalizedStates() {
stateSlice := make([][32]byte, 0, len(s.initSyncState))
// Add epoch boundary roots to slice.
for rt := range s.initSyncState {
stateSlice = append(stateSlice, rt)
}
// Sort by slots.
sort.Slice(stateSlice, func(i int, j int) bool {
return s.initSyncState[stateSlice[i]].Slot() < s.initSyncState[stateSlice[j]].Slot()
})
boundaryMap := make(map[[32]byte]bool)
for i := range s.boundaryRoots {
boundaryMap[s.boundaryRoots[i]] = true
}
for _, rt := range stateSlice[:initialSyncCacheSize] {
if boundaryMap[rt] {
continue
}
delete(s.initSyncState, rt)
}
}
func (s *Service) generateState(ctx context.Context, startRoot [32]byte, endRoot [32]byte) (*stateTrie.BeaconState, error) {
preState, err := s.beaconDB.State(ctx, startRoot)
if err != nil {
return nil, err
}
if preState == nil {
if !s.stateGen.HasState(ctx, startRoot) {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return nil, errors.Wrap(err, "could not save initial sync blocks")
}
s.clearInitSyncBlocks()
}
preState, err = s.stateGen.StateByRoot(ctx, startRoot)
if err != nil {
return nil, err
}
if preState == nil {
return nil, errors.New("finalized state does not exist in db")
}
}
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return nil, err
}
var endBlock *ethpb.SignedBeaconBlock
if !featureconfig.Get().NoInitSyncBatchSaveBlocks && s.hasInitSyncBlock(endRoot) {
endBlock = s.getInitSyncBlock(endRoot)
s.clearInitSyncBlocks()
} else {
endBlock, err = s.beaconDB.Block(ctx, endRoot)
if err != nil {
return nil, err
}
}
if endBlock == nil {
return nil, errors.New("provided block root does not have block saved in the db")
}
log.Warnf("Generating missing state of slot %d and root %#x", endBlock.Block.Slot, endRoot)
blocks, err := s.stateGen.LoadBlocks(ctx, preState.Slot()+1, endBlock.Block.Slot, endRoot)
if err != nil {
return nil, errors.Wrap(err, "could not load the required blocks")
}
postState, err := s.stateGen.ReplayBlocks(ctx, preState, blocks, endBlock.Block.Slot)
if err != nil {
return nil, errors.Wrap(err, "could not replay the blocks to generate the resultant state")
}
return postState, nil
}
// This saves a beacon block to the initial sync blocks cache.
func (s *Service) saveInitSyncBlock(r [32]byte, b *ethpb.SignedBeaconBlock) {
s.initSyncBlocksLock.Lock()

View File

@@ -1,318 +0,0 @@
package blockchain
import (
"context"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
messagediff "gopkg.in/d4l3k/messagediff.v1"
)
func TestFilterBoundaryCandidates_FilterCorrect(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
st, err := stateTrie.InitializeFromProtoUnsafe(&pb.BeaconState{})
if err != nil {
t.Fatal(err)
}
for i := uint64(0); i < 500; i++ {
if err := st.SetSlot(i); err != nil {
t.Fatal(err)
}
root := [32]byte{}
copy(root[:], bytesutil.Bytes32(i))
service.initSyncState[root] = st.Copy()
if helpers.IsEpochStart(i) {
service.boundaryRoots = append(service.boundaryRoots, root)
}
}
lastIndex := len(service.boundaryRoots) - 1
for i := uint64(500); i < 2000; i++ {
if err := st.SetSlot(i); err != nil {
t.Fatal(err)
}
root := [32]byte{}
copy(root[:], bytesutil.Bytes32(i))
service.initSyncState[root] = st.Copy()
}
// Set current state.
latestSlot := helpers.RoundUpToNearestEpoch(2000)
if err := st.SetSlot(latestSlot); err != nil {
t.Fatal(err)
}
lastRoot := [32]byte{}
copy(lastRoot[:], bytesutil.Bytes32(latestSlot))
service.initSyncState[lastRoot] = st.Copy()
service.finalizedCheckpt = &ethpb.Checkpoint{
Epoch: 0,
Root: []byte{},
}
service.filterBoundaryCandidates(context.Background(), lastRoot, st)
if len(service.boundaryRoots[lastIndex+1:]) == 0 {
t.Fatal("Wanted non zero added boundary roots")
}
for _, rt := range service.boundaryRoots[lastIndex+1:] {
st, ok := service.initSyncState[rt]
if !ok {
t.Error("Root doen't exist in cache map")
continue
}
if !(helpers.IsEpochStart(st.Slot()) || helpers.IsEpochStart(st.Slot()-1) || helpers.IsEpochStart(st.Slot()+1)) {
t.Errorf("boundary roots not validly stored. They have slot %d", st.Slot())
}
}
}
func TestFilterBoundaryCandidates_HandleSkippedSlots(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
st, err := stateTrie.InitializeFromProtoUnsafe(&pb.BeaconState{})
if err != nil {
t.Fatal(err)
}
for i := uint64(0); i < 500; i++ {
if err := st.SetSlot(i); err != nil {
t.Fatal(err)
}
root := [32]byte{}
copy(root[:], bytesutil.Bytes32(i))
service.initSyncState[root] = st.Copy()
if helpers.IsEpochStart(i) {
service.boundaryRoots = append(service.boundaryRoots, root)
}
}
lastIndex := len(service.boundaryRoots) - 1
for i := uint64(500); i < 2000; i++ {
if err := st.SetSlot(i); err != nil {
t.Fatal(err)
}
root := [32]byte{}
copy(root[:], bytesutil.Bytes32(i))
// save only for offsetted slots
if helpers.IsEpochStart(i + 10) {
service.initSyncState[root] = st.Copy()
}
}
// Set current state.
latestSlot := helpers.RoundUpToNearestEpoch(2000)
if err := st.SetSlot(latestSlot); err != nil {
t.Fatal(err)
}
lastRoot := [32]byte{}
copy(lastRoot[:], bytesutil.Bytes32(latestSlot))
service.initSyncState[lastRoot] = st.Copy()
service.finalizedCheckpt = &ethpb.Checkpoint{
Epoch: 0,
Root: []byte{},
}
service.filterBoundaryCandidates(context.Background(), lastRoot, st)
if len(service.boundaryRoots[lastIndex+1:]) == 0 {
t.Fatal("Wanted non zero added boundary roots")
}
for _, rt := range service.boundaryRoots[lastIndex+1:] {
st, ok := service.initSyncState[rt]
if !ok {
t.Error("Root doen't exist in cache map")
continue
}
if st.Slot() >= 500 {
// Ignore head boundary root.
if st.Slot() == 2016 {
continue
}
if !helpers.IsEpochStart(st.Slot() + 10) {
t.Errorf("boundary roots not validly stored. They have slot %d "+
"instead of the offset from epoch start", st.Slot())
}
}
}
}
func TestPruneOldStates_AlreadyFinalized(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
st, err := stateTrie.InitializeFromProtoUnsafe(&pb.BeaconState{})
if err != nil {
t.Fatal(err)
}
for i := uint64(100); i < 200; i++ {
if err := st.SetSlot(i); err != nil {
t.Fatal(err)
}
root := [32]byte{}
copy(root[:], bytesutil.Bytes32(i))
service.initSyncState[root] = st.Copy()
service.boundaryRoots = append(service.boundaryRoots, root)
}
finalizedEpoch := uint64(5)
service.finalizedCheckpt = &ethpb.Checkpoint{Epoch: finalizedEpoch}
service.pruneOldStates()
for _, rt := range service.boundaryRoots {
st, ok := service.initSyncState[rt]
if !ok {
t.Error("Root doen't exist in cache map")
continue
}
if st.Slot() < helpers.StartSlot(finalizedEpoch) {
t.Errorf("State with slot %d still exists and not pruned", st.Slot())
}
}
}
func TestPruneNonBoundary_CanPrune(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
st, err := stateTrie.InitializeFromProtoUnsafe(&pb.BeaconState{})
if err != nil {
t.Fatal(err)
}
for i := uint64(0); i < 2000; i++ {
if err := st.SetSlot(i); err != nil {
t.Fatal(err)
}
root := [32]byte{}
copy(root[:], bytesutil.Bytes32(i))
service.initSyncState[root] = st.Copy()
if helpers.IsEpochStart(i) {
service.boundaryRoots = append(service.boundaryRoots, root)
}
}
service.pruneNonBoundaryStates()
for _, rt := range service.boundaryRoots {
st, ok := service.initSyncState[rt]
if !ok {
t.Error("Root doesn't exist in cache map")
continue
}
if !helpers.IsEpochStart(st.Slot()) {
t.Errorf("Non boundary state with slot %d still exists and not pruned", st.Slot())
}
}
}
func TestGenerateState_CorrectlyGenerated(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
cfg := &Config{BeaconDB: db, StateGen: stategen.New(db, cache.NewStateSummaryCache())}
service, err := NewService(context.Background(), cfg)
if err != nil {
t.Fatal(err)
}
beaconState, privs := testutil.DeterministicGenesisState(t, 32)
genesisBlock := blocks.NewGenesisBlock([]byte{})
bodyRoot, err := ssz.HashTreeRoot(genesisBlock.Block)
if err != nil {
t.Fatal(err)
}
err = beaconState.SetLatestBlockHeader(&ethpb.BeaconBlockHeader{
Slot: genesisBlock.Block.Slot,
ParentRoot: genesisBlock.Block.ParentRoot,
StateRoot: params.BeaconConfig().ZeroHash[:],
BodyRoot: bodyRoot[:],
})
if err != nil {
t.Fatal(err)
}
if err := beaconState.SetSlashings(make([]uint64, params.BeaconConfig().EpochsPerSlashingsVector)); err != nil {
t.Fatal(err)
}
cp := beaconState.CurrentJustifiedCheckpoint()
mockRoot := [32]byte{}
copy(mockRoot[:], "hello-world")
cp.Root = mockRoot[:]
if err := beaconState.SetCurrentJustifiedCheckpoint(cp); err != nil {
t.Fatal(err)
}
if err := beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
err = db.SaveBlock(context.Background(), genesisBlock)
if err != nil {
t.Fatal(err)
}
genRoot, err := ssz.HashTreeRoot(genesisBlock)
if err != nil {
t.Fatal(err)
}
err = db.SaveState(context.Background(), beaconState, genRoot)
if err != nil {
t.Fatal(err)
}
lastBlock := &ethpb.SignedBeaconBlock{}
for i := uint64(1); i < 10; i++ {
block, err := testutil.GenerateFullBlock(beaconState, privs, testutil.DefaultBlockGenConfig(), i)
if err != nil {
t.Fatal(err)
}
beaconState, err = state.ExecuteStateTransition(context.Background(), beaconState, block)
if err != nil {
t.Fatal(err)
}
err = db.SaveBlock(context.Background(), block)
if err != nil {
t.Fatal(err)
}
lastBlock = block
}
root, err := ssz.HashTreeRoot(lastBlock.Block)
if err != nil {
t.Fatal(err)
}
newState, err := service.generateState(context.Background(), genRoot, root)
if err != nil {
t.Fatal(err)
}
if !ssz.DeepEqual(newState.InnerStateUnsafe(), beaconState.InnerStateUnsafe()) {
diff, _ := messagediff.PrettyDiff(newState.InnerStateUnsafe(), beaconState.InnerStateUnsafe())
t.Errorf("Generated state is different from what is expected: %s", diff)
}
}

View File

@@ -1,12 +1,11 @@
package blockchain
import (
"encoding/hex"
"fmt"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/sirupsen/logrus"
)
@@ -15,7 +14,6 @@ var log = logrus.WithField("prefix", "blockchain")
// logs state transition related data every slot.
func logStateTransitionData(b *ethpb.BeaconBlock) {
log.WithFields(logrus.Fields{
"slot": b.Slot,
"attestations": len(b.Body.Attestations),
"deposits": len(b.Body.Deposits),
"attesterSlashings": len(b.Body.AttesterSlashings),
@@ -24,29 +22,12 @@ func logStateTransitionData(b *ethpb.BeaconBlock) {
}).Info("Finished applying state transition")
}
func logEpochData(beaconState *stateTrie.BeaconState) {
func logBlockSyncStatus(block *ethpb.BeaconBlock, blockRoot [32]byte, finalized *ethpb.Checkpoint) {
log.WithFields(logrus.Fields{
"epoch": helpers.CurrentEpoch(beaconState),
"finalizedEpoch": beaconState.FinalizedCheckpointEpoch(),
"justifiedEpoch": beaconState.CurrentJustifiedCheckpoint().Epoch,
"previousJustifiedEpoch": beaconState.PreviousJustifiedCheckpoint().Epoch,
}).Info("Starting next epoch")
activeVals, err := helpers.ActiveValidatorIndices(beaconState, helpers.CurrentEpoch(beaconState))
if err != nil {
log.WithError(err).Error("Could not get active validator indices")
return
}
log.WithFields(logrus.Fields{
"totalValidators": len(beaconState.Validators()),
"activeValidators": len(activeVals),
"averageBalance": fmt.Sprintf("%.5f ETH", averageBalance(beaconState.Balances())),
}).Info("Validator registry information")
}
func averageBalance(balances []uint64) float64 {
total := uint64(0)
for i := 0; i < len(balances); i++ {
total += balances[i]
}
return float64(total) / float64(len(balances)) / float64(params.BeaconConfig().GweiPerEth)
"slot": block.Slot,
"block": fmt.Sprintf("0x%s...", hex.EncodeToString(blockRoot[:])[:8]),
"epoch": helpers.SlotToEpoch(block.Slot),
"finalizedEpoch": finalized.Epoch,
"finalizedRoot": fmt.Sprintf("0x%s...", hex.EncodeToString(finalized.Root[:])[:8]),
}).Info("Synced new block")
}

View File

@@ -1,13 +1,17 @@
package blockchain
import (
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/roughtime"
)
var (
@@ -19,10 +23,11 @@ var (
Name: "beacon_head_slot",
Help: "Slot of the head block of the beacon chain",
})
competingBlks = promauto.NewCounter(prometheus.CounterOpts{
Name: "competing_blocks",
Help: "The # of blocks received and processed from a competing chain",
clockTimeSlot = promauto.NewGauge(prometheus.GaugeOpts{
Name: "beacon_clock_time_slot",
Help: "The current slot based on the genesis time and current clock",
})
headFinalizedEpoch = promauto.NewGauge(prometheus.GaugeOpts{
Name: "head_finalized_epoch",
Help: "Last finalized epoch of the head state",
@@ -73,17 +78,36 @@ var (
})
totalEligibleBalances = promauto.NewGauge(prometheus.GaugeOpts{
Name: "total_eligible_balances",
Help: "The total amount of ether, in gwei, that has been used in voting attestation target of previous epoch",
Help: "The total amount of ether, in gwei, that is eligible for voting of previous epoch",
})
totalVotedTargetBalances = promauto.NewGauge(prometheus.GaugeOpts{
Name: "total_voted_target_balances",
Help: "The total amount of ether, in gwei, that is eligible for voting of previous epoch",
Help: "The total amount of ether, in gwei, that has been used in voting attestation target of previous epoch",
})
reorgCount = promauto.NewCounter(prometheus.CounterOpts{
Name: "beacon_reorg_total",
Help: "Count the number of times beacon chain has a reorg",
})
sentBlockPropagationHistogram = promauto.NewHistogram(
prometheus.HistogramOpts{
Name: "block_sent_latency_milliseconds",
Help: "Captures blocks broadcast time. Blocks sent in milliseconds distribution",
Buckets: []float64{1000, 2000, 3000, 4000, 5000, 6000},
},
)
attestationInclusionDelay = promauto.NewHistogram(
prometheus.HistogramOpts{
Name: "attestation_inclusion_delay_slots",
Help: "The number of slots between att.Slot and block.Slot",
Buckets: []float64{1, 2, 3, 4, 6, 32, 64},
},
)
)
// reportSlotMetrics reports slot related metrics.
func reportSlotMetrics(currentSlot uint64, headSlot uint64, finalizedCheckpoint *ethpb.Checkpoint) {
beaconSlot.Set(float64(currentSlot))
func reportSlotMetrics(stateSlot uint64, headSlot uint64, clockSlot uint64, finalizedCheckpoint *ethpb.Checkpoint) {
clockTimeSlot.Set(float64(clockSlot))
beaconSlot.Set(float64(stateSlot))
beaconHeadSlot.Set(float64(headSlot))
if finalizedCheckpoint != nil {
headFinalizedEpoch.Set(float64(finalizedCheckpoint.Epoch))
@@ -114,6 +138,7 @@ func reportEpochMetrics(state *stateTrie.BeaconState) {
for i, validator := range state.Validators() {
bal, err := state.BalanceAtIndex(uint64(i))
if err != nil {
log.Errorf("Could not load validator balance: %v", err)
continue
}
if validator.Slashed {
@@ -174,7 +199,25 @@ func reportEpochMetrics(state *stateTrie.BeaconState) {
currentEth1DataDepositCount.Set(float64(state.Eth1Data().DepositCount))
if precompute.Balances != nil {
totalEligibleBalances.Set(float64(precompute.Balances.PrevEpoch))
totalVotedTargetBalances.Set(float64(precompute.Balances.PrevEpochTargetAttesters))
totalEligibleBalances.Set(float64(precompute.Balances.ActivePrevEpoch))
totalVotedTargetBalances.Set(float64(precompute.Balances.PrevEpochTargetAttested))
}
}
// This captures metrics for block sent time by subtracts slot start time.
func captureSentTimeMetric(genesisTime uint64, currentSlot uint64) error {
startTime, err := helpers.SlotToTime(genesisTime, currentSlot)
if err != nil {
return err
}
diffMs := roughtime.Now().Sub(startTime) / time.Millisecond
sentBlockPropagationHistogram.Observe(float64(diffMs))
return nil
}
func reportAttestationInclusion(blk *ethpb.BeaconBlock) {
for _, att := range blk.Body.Attestations {
attestationInclusionDelay.Observe(float64(blk.Slot - att.Data.Slot))
}
}

View File

@@ -7,9 +7,9 @@ import (
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/flags"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/roughtime"
"go.opencensus.io/trace"
)
@@ -19,56 +19,30 @@ import (
var ErrTargetRootNotInDB = errors.New("target root does not exist in db")
// onAttestation is called whenever an attestation is received, verifies the attestation is valid and saves
/// it to the DB.
// it to the DB. As a stateless function, this does not hold nor delay attestation based on the spec descriptions.
// The delay is handled by the caller in `processAttestation`.
//
// Spec pseudocode definition:
// def on_attestation(store: Service, attestation: Attestation) -> None:
// def on_attestation(store: Store, attestation: Attestation) -> None:
// """
// Run ``on_attestation`` upon receiving a new ``attestation`` from either within a block or directly on the wire.
//
// An ``attestation`` that is asserted as invalid may be valid at a later time,
// consider scheduling it for later processing in such case.
// """
// target = attestation.data.target
// validate_on_attestation(store, attestation)
// store_target_checkpoint_state(store, attestation.data.target)
//
// # Attestations must be from the current or previous epoch
// current_epoch = compute_epoch_at_slot(get_current_slot(store))
// # Use GENESIS_EPOCH for previous when genesis to avoid underflow
// previous_epoch = current_epoch - 1 if current_epoch > GENESIS_EPOCH else GENESIS_EPOCH
// assert target.epoch in [current_epoch, previous_epoch]
// assert target.epoch == compute_epoch_at_slot(attestation.data.slot)
//
// # Attestations target be for a known block. If target block is unknown, delay consideration until the block is found
// assert target.root in store.blocks
// # Attestations cannot be from future epochs. If they are, delay consideration until the epoch arrives
// base_state = store.block_states[target.root].copy()
// assert store.time >= base_state.genesis_time + compute_start_slot_at_epoch(target.epoch) * SECONDS_PER_SLOT
//
// # Attestations must be for a known block. If block is unknown, delay consideration until the block is found
// assert attestation.data.beacon_block_root in store.blocks
// # Attestations must not be for blocks in the future. If not, the attestation should not be considered
// assert store.blocks[attestation.data.beacon_block_root].slot <= attestation.data.slot
//
// # Service target checkpoint state if not yet seen
// if target not in store.checkpoint_states:
// process_slots(base_state, compute_start_slot_at_epoch(target.epoch))
// store.checkpoint_states[target] = base_state
// target_state = store.checkpoint_states[target]
//
// # Attestations can only affect the fork choice of subsequent slots.
// # Delay consideration in the fork choice until their slot is in the past.
// assert store.time >= (attestation.data.slot + 1) * SECONDS_PER_SLOT
//
// # Get state at the `target` to validate attestation and calculate the committees
// # Get state at the `target` to fully validate attestation
// target_state = store.checkpoint_states[attestation.data.target]
// indexed_attestation = get_indexed_attestation(target_state, attestation)
// assert is_valid_indexed_attestation(target_state, indexed_attestation)
//
// # Update latest messages
// for i in indexed_attestation.attesting_indices:
// if i not in store.latest_messages or target.epoch > store.latest_messages[i].epoch:
// store.latest_messages[i] = LatestMessage(epoch=target.epoch, root=attestation.data.beacon_block_root)
// # Update latest messages for attesting indices
// update_latest_messages(store, indexed_attestation.attesting_indices, attestation)
// TODO(#6072): This code path is highly untested. Requires comprehensive tests and simpler refactoring.
func (s *Service) onAttestation(ctx context.Context, a *ethpb.Attestation) ([]uint64, error) {
ctx, span := trace.StartSpan(ctx, "blockchain.onAttestation")
ctx, span := trace.StartSpan(ctx, "blockChain.onAttestation")
defer span.End()
if a == nil {
@@ -82,7 +56,6 @@ func (s *Service) onAttestation(ctx context.Context, a *ethpb.Attestation) ([]ui
}
tgt := stateTrie.CopyCheckpoint(a.Data.Target)
tgtSlot := helpers.StartSlot(tgt.Epoch)
if helpers.SlotToEpoch(a.Data.Slot) != a.Data.Target.Epoch {
return nil, fmt.Errorf("data slot is not in the same epoch as target %d != %d", helpers.SlotToEpoch(a.Data.Slot), a.Data.Target.Epoch)
@@ -107,34 +80,27 @@ func (s *Service) onAttestation(ctx context.Context, a *ethpb.Attestation) ([]ui
return nil, err
}
// Verify Attestations cannot be from future epochs.
if err := helpers.VerifySlotTime(genesisTime, tgtSlot, helpers.TimeShiftTolerance); err != nil {
return nil, errors.Wrap(err, "could not verify attestation target slot")
}
// Verify attestation beacon block is known and not from the future.
if err := s.verifyBeaconBlock(ctx, a.Data); err != nil {
return nil, errors.Wrap(err, "could not verify attestation beacon block")
}
// Verify LMG GHOST and FFG votes are consistent with each other.
if err := s.verifyLMDFFGConsistent(ctx, a.Data.Target.Epoch, a.Data.Target.Root, a.Data.BeaconBlockRoot); err != nil {
return nil, errors.Wrap(err, "could not verify attestation beacon block")
}
// Verify attestations can only affect the fork choice of subsequent slots.
if err := helpers.VerifySlotTime(genesisTime, a.Data.Slot, helpers.TimeShiftTolerance); err != nil {
if err := helpers.VerifySlotTime(genesisTime, a.Data.Slot+1, params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil {
return nil, err
}
// Use the target state to to validate attestation and calculate the committees.
// Use the target state to validate attestation and calculate the committees.
indexedAtt, err := s.verifyAttestation(ctx, baseState, a)
if err != nil {
return nil, err
}
// Only save attestation in DB for archival node.
if flags.Get().EnableArchive {
if err := s.beaconDB.SaveAttestation(ctx, a); err != nil {
return nil, err
}
}
if indexedAtt.AttestingIndices == nil {
return nil, errors.New("nil attesting indices")
}

View File

@@ -3,7 +3,6 @@ package blockchain
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"github.com/pkg/errors"
@@ -15,7 +14,6 @@ import (
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/attestationutil"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
)
@@ -31,50 +29,13 @@ func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (*sta
return cachedState, nil
}
var baseState *stateTrie.BeaconState
if !featureconfig.Get().DisableNewStateMgmt {
if !s.stateGen.HasState(ctx, bytesutil.ToBytes32(c.Root)) {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return nil, errors.Wrap(err, "could not save initial sync blocks")
}
s.clearInitSyncBlocks()
}
baseState, err = s.stateGen.StateByRoot(ctx, bytesutil.ToBytes32(c.Root))
if err != nil {
return nil, errors.Wrapf(err, "could not get pre state for slot %d", helpers.StartSlot(c.Epoch))
}
} else {
if featureconfig.Get().CheckHeadState {
headRoot, err := s.HeadRoot(ctx)
if err != nil {
return nil, errors.Wrapf(err, "could not get head root")
}
if bytes.Equal(headRoot, c.Root) {
st, err := s.HeadState(ctx)
if err != nil {
return nil, errors.Wrapf(err, "could not get head state")
}
if err := s.checkpointState.AddCheckpointState(&cache.CheckpointState{
Checkpoint: c,
State: st.Copy(),
}); err != nil {
return nil, errors.Wrap(err, "could not saved checkpoint state to cache")
}
return st, nil
}
}
baseState, err = s.beaconDB.State(ctx, bytesutil.ToBytes32(c.Root))
if err != nil {
return nil, errors.Wrapf(err, "could not get pre state for slot %d", helpers.StartSlot(c.Epoch))
}
}
if baseState == nil {
return nil, fmt.Errorf("pre state of target block %d does not exist", helpers.StartSlot(c.Epoch))
baseState, err := s.stateGen.StateByRoot(ctx, bytesutil.ToBytes32(c.Root))
if err != nil {
return nil, errors.Wrapf(err, "could not get pre state for slot %d", helpers.StartSlot(c.Epoch))
}
if helpers.StartSlot(c.Epoch) > baseState.Slot() {
baseState = baseState.Copy()
baseState, err = state.ProcessSlots(ctx, baseState, helpers.StartSlot(c.Epoch))
if err != nil {
return nil, errors.Wrapf(err, "could not process slots up to %d", helpers.StartSlot(c.Epoch))
@@ -83,12 +44,13 @@ func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (*sta
if err := s.checkpointState.AddCheckpointState(&cache.CheckpointState{
Checkpoint: c,
State: baseState.Copy(),
State: baseState,
}); err != nil {
return nil, errors.Wrap(err, "could not saved checkpoint state to cache")
}
return baseState, nil
}
// verifyAttTargetEpoch validates attestation is from the current or previous epoch.
@@ -108,10 +70,16 @@ func (s *Service) verifyAttTargetEpoch(ctx context.Context, genesisTime uint64,
// verifyBeaconBlock verifies beacon head block is known and not from the future.
func (s *Service) verifyBeaconBlock(ctx context.Context, data *ethpb.AttestationData) error {
b, err := s.beaconDB.Block(ctx, bytesutil.ToBytes32(data.BeaconBlockRoot))
r := bytesutil.ToBytes32(data.BeaconBlockRoot)
b, err := s.beaconDB.Block(ctx, r)
if err != nil {
return err
}
// If the block does not exist in db, check again if block exists in initial sync block cache.
// This could happen as the node first syncs to head.
if b == nil && s.hasInitSyncBlock(r) {
b = s.getInitSyncBlock(r)
}
if b == nil || b.Block == nil {
return fmt.Errorf("beacon block %#x does not exist", bytesutil.Trunc(data.BeaconBlockRoot))
}
@@ -121,6 +89,20 @@ func (s *Service) verifyBeaconBlock(ctx context.Context, data *ethpb.Attestation
return nil
}
// verifyLMDFFGConsistent verifies LMD GHOST and FFG votes are consistent with each other.
func (s *Service) verifyLMDFFGConsistent(ctx context.Context, ffgEpoch uint64, ffgRoot []byte, lmdRoot []byte) error {
ffgSlot := helpers.StartSlot(ffgEpoch)
r, err := s.ancestor(ctx, lmdRoot, ffgSlot)
if err != nil {
return err
}
if !bytes.Equal(ffgRoot, r) {
return errors.New("FFG and LMD votes are not consistent")
}
return nil
}
// verifyAttestation validates input attestation is valid.
func (s *Service) verifyAttestation(ctx context.Context, baseState *stateTrie.BeaconState, a *ethpb.Attestation) (*ethpb.IndexedAttestation, error) {
committee, err := helpers.BeaconCommitteeFromState(baseState, a.Data.Slot, a.Data.CommitteeIndex)
@@ -129,48 +111,7 @@ func (s *Service) verifyAttestation(ctx context.Context, baseState *stateTrie.Be
}
indexedAtt := attestationutil.ConvertToIndexed(ctx, a, committee)
if err := blocks.VerifyIndexedAttestation(ctx, baseState, indexedAtt); err != nil {
if err == helpers.ErrSigFailedToVerify {
// When sig fails to verify, check if there's a differences in committees due to
// different seeds.
var aState *stateTrie.BeaconState
var err error
if !featureconfig.Get().DisableNewStateMgmt {
if !s.stateGen.HasState(ctx, bytesutil.ToBytes32(a.Data.BeaconBlockRoot)) {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return nil, errors.Wrap(err, "could not save initial sync blocks")
}
s.clearInitSyncBlocks()
}
aState, err = s.stateGen.StateByRoot(ctx, bytesutil.ToBytes32(a.Data.BeaconBlockRoot))
if err != nil {
return nil, err
}
} else {
aState, err = s.beaconDB.State(ctx, bytesutil.ToBytes32(a.Data.BeaconBlockRoot))
if err != nil {
return nil, err
}
}
if aState == nil {
return nil, fmt.Errorf("nil state for block root %#x", a.Data.BeaconBlockRoot)
}
epoch := helpers.SlotToEpoch(a.Data.Slot)
origSeed, err := helpers.Seed(baseState, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return nil, errors.Wrap(err, "could not get original seed")
}
aSeed, err := helpers.Seed(aState, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return nil, errors.Wrap(err, "could not get attester's seed")
}
if origSeed != aSeed {
return nil, fmt.Errorf("could not verify indexed attestation due to differences in seeds: %v != %v",
hex.EncodeToString(bytesutil.Trunc(origSeed[:])), hex.EncodeToString(bytesutil.Trunc(aSeed[:])))
}
}
return nil, errors.Wrap(err, "could not verify indexed attestation")
}
return indexedAtt, nil
}

View File

@@ -7,75 +7,55 @@ import (
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestStore_OnAttestation(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
cfg := &Config{
BeaconDB: db,
ForkChoiceStore: protoarray.New(0, 0, [32]byte{}),
StateGen: stategen.New(db, cache.NewStateSummaryCache()),
StateGen: stategen.New(db, sc),
}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
_, err = blockTree1(db, []byte{'g'})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
BlkWithOutState := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 0}}
if err := db.SaveBlock(ctx, BlkWithOutState); err != nil {
t.Fatal(err)
}
BlkWithOutStateRoot, err := ssz.HashTreeRoot(BlkWithOutState.Block)
if err != nil {
t.Fatal(err)
}
require.NoError(t, db.SaveBlock(ctx, BlkWithOutState))
BlkWithOutStateRoot, err := stateutil.BlockRoot(BlkWithOutState.Block)
require.NoError(t, err)
BlkWithStateBadAtt := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 1}}
if err := db.SaveBlock(ctx, BlkWithStateBadAtt); err != nil {
t.Fatal(err)
}
BlkWithStateBadAttRoot, err := ssz.HashTreeRoot(BlkWithStateBadAtt.Block)
if err != nil {
t.Fatal(err)
}
require.NoError(t, db.SaveBlock(ctx, BlkWithStateBadAtt))
BlkWithStateBadAttRoot, err := stateutil.BlockRoot(BlkWithStateBadAtt.Block)
require.NoError(t, err)
s := testutil.NewBeaconState()
if err := s.SetSlot(100 * params.BeaconConfig().SlotsPerEpoch); err != nil {
t.Fatal(err)
}
if err := service.beaconDB.SaveState(ctx, s, BlkWithStateBadAttRoot); err != nil {
t.Fatal(err)
}
require.NoError(t, s.SetSlot(100*params.BeaconConfig().SlotsPerEpoch))
require.NoError(t, service.beaconDB.SaveState(ctx, s, BlkWithStateBadAttRoot))
BlkWithValidState := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 2}}
if err := db.SaveBlock(ctx, BlkWithValidState); err != nil {
t.Fatal(err)
}
require.NoError(t, db.SaveBlock(ctx, BlkWithValidState))
BlkWithValidStateRoot, err := ssz.HashTreeRoot(BlkWithValidState.Block)
if err != nil {
t.Fatal(err)
}
BlkWithValidStateRoot, err := stateutil.BlockRoot(BlkWithValidState.Block)
require.NoError(t, err)
s = testutil.NewBeaconState()
if err := s.SetFork(&pb.Fork{
Epoch: 0,
@@ -84,9 +64,7 @@ func TestStore_OnAttestation(t *testing.T) {
}); err != nil {
t.Fatal(err)
}
if err := service.beaconDB.SaveState(ctx, s, BlkWithValidStateRoot); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, s, BlkWithValidStateRoot))
tests := []struct {
name string
@@ -114,7 +92,7 @@ func TestStore_OnAttestation(t *testing.T) {
a: &ethpb.Attestation{Data: &ethpb.AttestationData{Target: &ethpb.Checkpoint{Root: BlkWithOutStateRoot[:]}}},
s: &pb.BeaconState{},
wantErr: true,
wantErrString: "could not get pre state for slot 0: could not get ancestor state",
wantErrString: "could not get pre state for slot 0",
},
{
name: "process attestation doesn't match current epoch",
@@ -122,7 +100,7 @@ func TestStore_OnAttestation(t *testing.T) {
Root: BlkWithStateBadAttRoot[:]}}},
s: &pb.BeaconState{Slot: 100 * params.BeaconConfig().SlotsPerEpoch},
wantErr: true,
wantErrString: "does not match current epoch",
wantErrString: "target epoch 100 does not match current epoch",
},
{
name: "process nil field (a.Target) in attestation",
@@ -163,17 +141,14 @@ func TestStore_OnAttestation(t *testing.T) {
func TestStore_SaveCheckpointState(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
cfg := &Config{
BeaconDB: db,
StateGen: stategen.New(db, cache.NewStateSummaryCache()),
StateGen: stategen.New(db, sc),
}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
s, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Fork: &pb.Fork{
@@ -191,13 +166,9 @@ func TestStore_SaveCheckpointState(t *testing.T) {
Validators: []*ethpb.Validator{{PublicKey: bytesutil.PadTo([]byte("foo"), 48)}},
Balances: []uint64{0},
})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
r := [32]byte{'g'}
if err := service.beaconDB.SaveState(ctx, s, r); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, s, r))
service.justifiedCheckpt = &ethpb.Checkpoint{Root: r[:]}
service.bestJustifiedCheckpt = &ethpb.Checkpoint{Root: r[:]}
@@ -206,142 +177,80 @@ func TestStore_SaveCheckpointState(t *testing.T) {
r = bytesutil.ToBytes32([]byte{'A'})
cp1 := &ethpb.Checkpoint{Epoch: 1, Root: bytesutil.PadTo([]byte{'A'}, 32)}
if err := service.beaconDB.SaveState(ctx, s, bytesutil.ToBytes32([]byte{'A'})); err != nil {
t.Fatal(err)
}
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: bytesutil.PadTo([]byte{'A'}, 32)}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, s, bytesutil.ToBytes32([]byte{'A'})))
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: bytesutil.PadTo([]byte{'A'}, 32)}))
s1, err := service.getAttPreState(ctx, cp1)
if err != nil {
t.Fatal(err)
}
if s1.Slot() != 1*params.BeaconConfig().SlotsPerEpoch {
t.Errorf("Wanted state slot: %d, got: %d", 1*params.BeaconConfig().SlotsPerEpoch, s1.Slot())
}
require.NoError(t, err)
assert.Equal(t, 1*params.BeaconConfig().SlotsPerEpoch, s1.Slot(), "Unexpected state slot")
cp2 := &ethpb.Checkpoint{Epoch: 2, Root: bytesutil.PadTo([]byte{'B'}, 32)}
if err := service.beaconDB.SaveState(ctx, s, bytesutil.ToBytes32([]byte{'B'})); err != nil {
t.Fatal(err)
}
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: bytesutil.PadTo([]byte{'B'}, 32)}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, s, bytesutil.ToBytes32([]byte{'B'})))
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: bytesutil.PadTo([]byte{'B'}, 32)}))
s2, err := service.getAttPreState(ctx, cp2)
if err != nil {
t.Fatal(err)
}
if s2.Slot() != 2*params.BeaconConfig().SlotsPerEpoch {
t.Errorf("Wanted state slot: %d, got: %d", 2*params.BeaconConfig().SlotsPerEpoch, s2.Slot())
}
require.NoError(t, err)
assert.Equal(t, 2*params.BeaconConfig().SlotsPerEpoch, s2.Slot(), "Unexpected state slot")
s1, err = service.getAttPreState(ctx, cp1)
if err != nil {
t.Fatal(err)
}
if s1.Slot() != 1*params.BeaconConfig().SlotsPerEpoch {
t.Errorf("Wanted state slot: %d, got: %d", 1*params.BeaconConfig().SlotsPerEpoch, s1.Slot())
}
require.NoError(t, err)
assert.Equal(t, 1*params.BeaconConfig().SlotsPerEpoch, s1.Slot(), "Unexpected state slot")
s1, err = service.checkpointState.StateByCheckpoint(cp1)
if err != nil {
t.Fatal(err)
}
if s1.Slot() != 1*params.BeaconConfig().SlotsPerEpoch {
t.Errorf("Wanted state slot: %d, got: %d", 1*params.BeaconConfig().SlotsPerEpoch, s1.Slot())
}
require.NoError(t, err)
assert.Equal(t, 1*params.BeaconConfig().SlotsPerEpoch, s1.Slot(), "Unexpected state slot")
s2, err = service.checkpointState.StateByCheckpoint(cp2)
if err != nil {
t.Fatal(err)
}
if s2.Slot() != 2*params.BeaconConfig().SlotsPerEpoch {
t.Errorf("Wanted state slot: %d, got: %d", 2*params.BeaconConfig().SlotsPerEpoch, s2.Slot())
}
require.NoError(t, err)
assert.Equal(t, 2*params.BeaconConfig().SlotsPerEpoch, s2.Slot(), "Unexpected state slot")
if err := s.SetSlot(params.BeaconConfig().SlotsPerEpoch + 1); err != nil {
t.Fatal(err)
}
require.NoError(t, s.SetSlot(params.BeaconConfig().SlotsPerEpoch+1))
service.justifiedCheckpt = &ethpb.Checkpoint{Root: r[:]}
service.bestJustifiedCheckpt = &ethpb.Checkpoint{Root: r[:]}
service.finalizedCheckpt = &ethpb.Checkpoint{Root: r[:]}
service.prevFinalizedCheckpt = &ethpb.Checkpoint{Root: r[:]}
cp3 := &ethpb.Checkpoint{Epoch: 1, Root: bytesutil.PadTo([]byte{'C'}, 32)}
if err := service.beaconDB.SaveState(ctx, s, bytesutil.ToBytes32([]byte{'C'})); err != nil {
t.Fatal(err)
}
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: bytesutil.PadTo([]byte{'C'}, 32)}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, s, bytesutil.ToBytes32([]byte{'C'})))
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: bytesutil.PadTo([]byte{'C'}, 32)}))
s3, err := service.getAttPreState(ctx, cp3)
if err != nil {
t.Fatal(err)
}
if s3.Slot() != s.Slot() {
t.Errorf("Wanted state slot: %d, got: %d", s.Slot(), s3.Slot())
}
require.NoError(t, err)
assert.Equal(t, s.Slot(), s3.Slot(), "Unexpected state slot")
}
func TestStore_UpdateCheckpointState(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
cfg := &Config{
BeaconDB: db,
StateGen: stategen.New(db, cache.NewStateSummaryCache()),
StateGen: stategen.New(db, sc),
}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
epoch := uint64(1)
baseState, _ := testutil.DeterministicGenesisState(t, 1)
if err := baseState.SetSlot(epoch * params.BeaconConfig().SlotsPerEpoch); err != nil {
t.Fatal(err)
}
require.NoError(t, baseState.SetSlot(epoch*params.BeaconConfig().SlotsPerEpoch))
checkpoint := &ethpb.Checkpoint{Epoch: epoch}
if err := service.beaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(checkpoint.Root)); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(checkpoint.Root)))
returned, err := service.getAttPreState(ctx, checkpoint)
if err != nil {
t.Fatal(err)
}
if baseState.Slot() != returned.Slot() {
t.Error("Incorrectly returned base state")
}
require.NoError(t, err)
assert.Equal(t, returned.Slot(), baseState.Slot(), "Incorrectly returned base state")
cached, err := service.checkpointState.StateByCheckpoint(checkpoint)
if err != nil {
t.Fatal(err)
}
if cached == nil {
t.Error("State should have been cached")
}
require.NoError(t, err)
assert.NotNil(t, cached, "State should have been cached")
epoch = uint64(2)
newCheckpoint := &ethpb.Checkpoint{Epoch: epoch}
if err := service.beaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(newCheckpoint.Root)); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, baseState, bytesutil.ToBytes32(newCheckpoint.Root)))
returned, err = service.getAttPreState(ctx, newCheckpoint)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
baseState, err = state.ProcessSlots(ctx, baseState, helpers.StartSlot(newCheckpoint.Epoch))
if err != nil {
t.Fatal(err)
}
if baseState.Slot() != returned.Slot() {
t.Error("Incorrectly returned base state")
}
require.NoError(t, err)
assert.Equal(t, returned.Slot(), baseState.Slot(), "Incorrectly returned base state")
cached, err = service.checkpointState.StateByCheckpoint(newCheckpoint)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if !proto.Equal(returned.InnerStateUnsafe(), cached.InnerStateUnsafe()) {
t.Error("Incorrectly cached base state")
}
@@ -349,14 +258,11 @@ func TestStore_UpdateCheckpointState(t *testing.T) {
func TestAttEpoch_MatchPrevEpoch(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if err := service.verifyAttTargetEpoch(
ctx,
@@ -369,14 +275,11 @@ func TestAttEpoch_MatchPrevEpoch(t *testing.T) {
func TestAttEpoch_MatchCurrentEpoch(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if err := service.verifyAttTargetEpoch(
ctx,
@@ -389,14 +292,11 @@ func TestAttEpoch_MatchCurrentEpoch(t *testing.T) {
func TestAttEpoch_NotMatch(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if err := service.verifyAttTargetEpoch(
ctx,
@@ -410,70 +310,88 @@ func TestAttEpoch_NotMatch(t *testing.T) {
func TestVerifyBeaconBlock_NoBlock(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
d := &ethpb.AttestationData{}
if err := service.verifyBeaconBlock(ctx, d); !strings.Contains(err.Error(), "beacon block does not exist") {
t.Error("Did not receive the wanted error")
}
assert.ErrorContains(t, "beacon block does not exist", service.verifyBeaconBlock(ctx, d))
}
func TestVerifyBeaconBlock_futureBlock(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
b := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 2}}
if err := service.beaconDB.SaveBlock(ctx, b); err != nil {
t.Fatal(err)
}
r, err := ssz.HashTreeRoot(b.Block)
if err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveBlock(ctx, b))
r, err := stateutil.BlockRoot(b.Block)
require.NoError(t, err)
d := &ethpb.AttestationData{Slot: 1, BeaconBlockRoot: r[:]}
err = service.verifyBeaconBlock(ctx, d)
if err == nil || !strings.Contains(err.Error(), "could not process attestation for future block") {
t.Error("Did not receive the wanted error")
}
assert.ErrorContains(t, "could not process attestation for future block", service.verifyBeaconBlock(ctx, d))
}
func TestVerifyBeaconBlock_OK(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
cfg := &Config{BeaconDB: db}
service, err := NewService(ctx, cfg)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
b := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 2}}
if err := service.beaconDB.SaveBlock(ctx, b); err != nil {
t.Fatal(err)
}
r, err := ssz.HashTreeRoot(b.Block)
if err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveBlock(ctx, b))
r, err := stateutil.BlockRoot(b.Block)
require.NoError(t, err)
d := &ethpb.AttestationData{Slot: 2, BeaconBlockRoot: r[:]}
if err := service.verifyBeaconBlock(ctx, d); err != nil {
t.Error("Did not receive the wanted error")
}
assert.NoError(t, service.verifyBeaconBlock(ctx, d), "Did not receive the wanted error")
}
func TestVerifyLMDFFGConsistent_NotOK(t *testing.T) {
ctx := context.Background()
db, _ := testDB.SetupDB(t)
cfg := &Config{BeaconDB: db, ForkChoiceStore: protoarray.New(0, 0, [32]byte{})}
service, err := NewService(ctx, cfg)
require.NoError(t, err)
b32 := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 32}}
require.NoError(t, service.beaconDB.SaveBlock(ctx, b32))
r32, err := stateutil.BlockRoot(b32.Block)
require.NoError(t, err)
b33 := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 33, ParentRoot: r32[:]}}
require.NoError(t, service.beaconDB.SaveBlock(ctx, b33))
r33, err := stateutil.BlockRoot(b33.Block)
require.NoError(t, err)
wanted := "FFG and LMD votes are not consistent"
assert.ErrorContains(t, wanted, service.verifyLMDFFGConsistent(context.Background(), 1, []byte{'a'}, r33[:]))
}
func TestVerifyLMDFFGConsistent_OK(t *testing.T) {
ctx := context.Background()
db, _ := testDB.SetupDB(t)
cfg := &Config{BeaconDB: db, ForkChoiceStore: protoarray.New(0, 0, [32]byte{})}
service, err := NewService(ctx, cfg)
require.NoError(t, err)
b32 := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 32}}
require.NoError(t, service.beaconDB.SaveBlock(ctx, b32))
r32, err := stateutil.BlockRoot(b32.Block)
require.NoError(t, err)
b33 := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 33, ParentRoot: r32[:]}}
require.NoError(t, service.beaconDB.SaveBlock(ctx, b33))
r33, err := stateutil.BlockRoot(b33.Block)
require.NoError(t, err)
err = service.verifyLMDFFGConsistent(context.Background(), 1, r32[:], r33[:])
assert.NoError(t, err, "Could not verify LMD and FFG votes to be consistent")
}

View File

@@ -2,21 +2,18 @@ package blockchain
import (
"context"
"encoding/hex"
"fmt"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"
"github.com/prysmaticlabs/prysm/beacon-chain/flags"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
"github.com/prysmaticlabs/prysm/shared/attestationutil"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
@@ -24,175 +21,120 @@ import (
var initialSyncBlockCacheSize = 2 * params.BeaconConfig().SlotsPerEpoch
// onBlock is called when a gossip block is received. It runs regular state transition on the block.
// The block's signing root should be computed before calling this method to avoid redundant
// computation in this method and methods it calls into.
//
// Spec pseudocode definition:
// def on_block(store: Store, block: BeaconBlock) -> None:
// # Make a copy of the state to avoid mutability issues
// def on_block(store: Store, signed_block: SignedBeaconBlock) -> None:
// block = signed_block.message
// # Parent block must be known
// assert block.parent_root in store.block_states
// pre_state = store.block_states[block.parent_root].copy()
// # Make a copy of the state to avoid mutability issues
// pre_state = copy(store.block_states[block.parent_root])
// # Blocks cannot be in the future. If they are, their consideration must be delayed until the are in the past.
// assert store.time >= pre_state.genesis_time + block.slot * SECONDS_PER_SLOT
// # Add new block to the store
// store.blocks[signing_root(block)] = block
// # Check block is a descendant of the finalized block
// assert (
// get_ancestor(store, signing_root(block), store.blocks[store.finalized_checkpoint.root].slot) ==
// store.finalized_checkpoint.root
// )
// # Check that block is later than the finalized epoch slot
// assert block.slot > compute_start_slot_of_epoch(store.finalized_checkpoint.epoch)
// assert get_current_slot(store) >= block.slot
//
// # Check that block is later than the finalized epoch slot (optimization to reduce calls to get_ancestor)
// finalized_slot = compute_start_slot_at_epoch(store.finalized_checkpoint.epoch)
// assert block.slot > finalized_slot
// # Check block is a descendant of the finalized block at the checkpoint finalized slot
// assert get_ancestor(store, block.parent_root, finalized_slot) == store.finalized_checkpoint.root
//
// # Check the block is valid and compute the post-state
// state = state_transition(pre_state, block)
// state = state_transition(pre_state, signed_block, True)
// # Add new block to the store
// store.blocks[hash_tree_root(block)] = block
// # Add new state for this block to the store
// store.block_states[signing_root(block)] = state
// store.block_states[hash_tree_root(block)] = state
//
// # Update justified checkpoint
// if state.current_justified_checkpoint.epoch > store.justified_checkpoint.epoch:
// if state.current_justified_checkpoint.epoch > store.best_justified_checkpoint.epoch:
// store.best_justified_checkpoint = state.current_justified_checkpoint
// if should_update_justified_checkpoint(store, state.current_justified_checkpoint):
// store.justified_checkpoint = state.current_justified_checkpoint
//
// # Update finalized checkpoint
// if state.finalized_checkpoint.epoch > store.finalized_checkpoint.epoch:
// store.finalized_checkpoint = state.finalized_checkpoint
func (s *Service) onBlock(ctx context.Context, signed *ethpb.SignedBeaconBlock) (*stateTrie.BeaconState, error) {
ctx, span := trace.StartSpan(ctx, "blockchain.onBlock")
//
// # Potentially update justified if different from store
// if store.justified_checkpoint != state.current_justified_checkpoint:
// # Update justified if new justified is later than store justified
// if state.current_justified_checkpoint.epoch > store.justified_checkpoint.epoch:
// store.justified_checkpoint = state.current_justified_checkpoint
// return
//
// # Update justified if store justified is not in chain with finalized checkpoint
// finalized_slot = compute_start_slot_at_epoch(store.finalized_checkpoint.epoch)
// ancestor_at_finalized_slot = get_ancestor(store, store.justified_checkpoint.root, finalized_slot)
// if ancestor_at_finalized_slot != store.finalized_checkpoint.root:
// store.justified_checkpoint = state.current_justified_checkpoint
func (s *Service) onBlock(ctx context.Context, signed *ethpb.SignedBeaconBlock, blockRoot [32]byte) error {
ctx, span := trace.StartSpan(ctx, "blockChain.onBlock")
defer span.End()
if signed == nil || signed.Block == nil {
return nil, errors.New("nil block")
return errors.New("nil block")
}
b := signed.Block
// Retrieve incoming block's pre state.
preState, err := s.getBlockPreState(ctx, b)
if err != nil {
return nil, err
return err
}
root, err := stateutil.BlockRoot(b)
if err != nil {
return nil, errors.Wrapf(err, "could not get signing root of block %d", b.Slot)
}
log.WithFields(logrus.Fields{
"slot": b.Slot,
"root": fmt.Sprintf("0x%s...", hex.EncodeToString(root[:])[:8]),
}).Info("Executing state transition on block")
postState, err := state.ExecuteStateTransition(ctx, preState, signed)
if err != nil {
return nil, errors.Wrap(err, "could not execute state transition")
return errors.Wrap(err, "could not execute state transition")
}
if err := s.beaconDB.SaveBlock(ctx, signed); err != nil {
return nil, errors.Wrapf(err, "could not save block from slot %d", b.Slot)
}
if err := s.insertBlockToForkChoiceStore(ctx, b, root, postState); err != nil {
return nil, errors.Wrapf(err, "could not insert block %d to fork choice store", b.Slot)
}
if !featureconfig.Get().DisableNewStateMgmt {
if err := s.stateGen.SaveState(ctx, root, postState); err != nil {
return nil, errors.Wrap(err, "could not save state")
}
} else {
if err := s.beaconDB.SaveState(ctx, postState, root); err != nil {
return nil, errors.Wrap(err, "could not save state")
}
if err := s.savePostStateInfo(ctx, blockRoot, signed, postState, false /* reg sync */); err != nil {
return err
}
// Update justified check point.
if postState.CurrentJustifiedCheckpoint().Epoch > s.justifiedCheckpt.Epoch {
if err := s.updateJustified(ctx, postState); err != nil {
return nil, err
return err
}
}
// Update finalized check point. Prune the block cache and helper caches on every new finalized epoch.
// Update finalized check point.
if postState.FinalizedCheckpointEpoch() > s.finalizedCheckpt.Epoch {
if !featureconfig.Get().NoInitSyncBatchSaveBlocks {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return nil, err
}
s.clearInitSyncBlocks()
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return err
}
s.clearInitSyncBlocks()
if err := s.updateFinalized(ctx, postState.FinalizedCheckpoint()); err != nil {
return err
}
if err := s.beaconDB.SaveFinalizedCheckpoint(ctx, postState.FinalizedCheckpoint()); err != nil {
return nil, errors.Wrap(err, "could not save finalized checkpoint")
}
if featureconfig.Get().DisableNewStateMgmt {
startSlot := helpers.StartSlot(s.prevFinalizedCheckpt.Epoch)
endSlot := helpers.StartSlot(s.finalizedCheckpt.Epoch)
if endSlot > startSlot {
if err := s.rmStatesOlderThanLastFinalized(ctx, startSlot, endSlot); err != nil {
return nil, errors.Wrapf(err, "could not delete states prior to finalized check point, range: %d, %d",
startSlot, endSlot)
}
}
}
fRoot := bytesutil.ToBytes32(postState.FinalizedCheckpoint().Root)
// Prune proto array fork choice nodes, all nodes before finalized check point will
// be pruned.
if err := s.forkChoiceStore.Prune(ctx, fRoot); err != nil {
return nil, errors.Wrap(err, "could not prune proto array fork choice nodes")
return errors.Wrap(err, "could not prune proto array fork choice nodes")
}
s.prevFinalizedCheckpt = s.finalizedCheckpt
s.finalizedCheckpt = postState.FinalizedCheckpoint()
if err := s.finalizedImpliesNewJustified(ctx, postState); err != nil {
return nil, errors.Wrap(err, "could not save new justified")
return errors.Wrap(err, "could not save new justified")
}
if !featureconfig.Get().DisableNewStateMgmt {
fRoot := bytesutil.ToBytes32(postState.FinalizedCheckpoint().Root)
fBlock, err := s.beaconDB.Block(ctx, fRoot)
if err != nil {
return nil, errors.Wrap(err, "could not get finalized block to migrate")
}
if err := s.stateGen.MigrateToCold(ctx, fBlock.Block.Slot, fRoot); err != nil {
return nil, errors.Wrap(err, "could not migrate to cold")
}
}
// Update deposit cache.
s.depositCache.InsertFinalizedDeposits(ctx, int64(postState.Eth1DepositIndex()))
}
// Epoch boundary bookkeeping such as logging epoch summaries.
if postState.Slot() >= s.nextEpochBoundarySlot {
logEpochData(postState)
reportEpochMetrics(postState)
defer reportAttestationInclusion(b)
// Update committees cache at epoch boundary slot.
if err := helpers.UpdateCommitteeCache(postState, helpers.CurrentEpoch(postState)); err != nil {
return nil, err
}
if err := helpers.UpdateProposerIndicesInCache(postState, helpers.CurrentEpoch(postState)); err != nil {
return nil, err
}
s.nextEpochBoundarySlot = helpers.StartSlot(helpers.NextEpoch(postState))
}
// Delete the processed block attestations from attestation pool.
if err := s.deletePoolAtts(b.Body.Attestations); err != nil {
return nil, err
}
// Delete the processed block attester slashings from slashings pool.
for i := 0; i < len(b.Body.AttesterSlashings); i++ {
s.slashingPool.MarkIncludedAttesterSlashing(b.Body.AttesterSlashings[i])
}
return postState, nil
return s.handleEpochBoundary(postState)
}
// onBlockInitialSyncStateTransition is called when an initial sync block is received.
// It runs state transition on the block and without any BLS verification. The excluded BLS verification
// includes attestation's aggregated signature. It also does not save attestations.
func (s *Service) onBlockInitialSyncStateTransition(ctx context.Context, signed *ethpb.SignedBeaconBlock) error {
ctx, span := trace.StartSpan(ctx, "blockchain.onBlock")
// It runs state transition on the block and without fork choice and post operation pool processes.
// The block's signing root should be computed before calling this method to avoid redundant
// computation in this method and methods it calls into.
func (s *Service) onBlockInitialSyncStateTransition(ctx context.Context, signed *ethpb.SignedBeaconBlock, blockRoot [32]byte) error {
ctx, span := trace.StartSpan(ctx, "blockChain.onBlockInitialSyncStateTransition")
defer span.End()
if signed == nil || signed.Block == nil {
@@ -202,130 +144,176 @@ func (s *Service) onBlockInitialSyncStateTransition(ctx context.Context, signed
b := signed.Block
// Retrieve incoming block's pre state.
preState, err := s.verifyBlkPreState(ctx, b)
if err := s.verifyBlkPreState(ctx, b); err != nil {
return err
}
preState, err := s.stateGen.StateByRootInitialSync(ctx, bytesutil.ToBytes32(signed.Block.ParentRoot))
if err != nil {
return err
}
if preState == nil {
return fmt.Errorf("nil pre state for slot %d", b.Slot)
}
// Exit early if the pre state slot is higher than incoming block's slot.
if preState.Slot() >= signed.Block.Slot {
return nil
}
postState, err := state.ExecuteStateTransitionNoVerifyAttSigs(ctx, preState, signed)
var postState *stateTrie.BeaconState
if featureconfig.Get().InitSyncNoVerify {
postState, err = state.ExecuteStateTransitionNoVerifyAttSigs(ctx, preState, signed)
} else {
postState, err = state.ExecuteStateTransition(ctx, preState, signed)
}
if err != nil {
return errors.Wrap(err, "could not execute state transition")
}
root, err := stateutil.BlockRoot(b)
if err != nil {
return errors.Wrapf(err, "could not get signing root of block %d", b.Slot)
if err := s.savePostStateInfo(ctx, blockRoot, signed, postState, true /* init sync */); err != nil {
return err
}
if !featureconfig.Get().NoInitSyncBatchSaveBlocks {
s.saveInitSyncBlock(root, signed)
} else {
if err := s.beaconDB.SaveBlock(ctx, signed); err != nil {
return errors.Wrapf(err, "could not save block from slot %d", b.Slot)
}
}
if err := s.insertBlockToForkChoiceStore(ctx, b, root, postState); err != nil {
return errors.Wrapf(err, "could not insert block %d to fork choice store", b.Slot)
}
if !featureconfig.Get().DisableNewStateMgmt {
if err := s.stateGen.SaveState(ctx, root, postState); err != nil {
return errors.Wrap(err, "could not save state")
}
} else {
s.initSyncStateLock.Lock()
defer s.initSyncStateLock.Unlock()
s.initSyncState[root] = postState.Copy()
s.filterBoundaryCandidates(ctx, root, postState)
}
if flags.Get().EnableArchive {
atts := signed.Block.Body.Attestations
if err := s.beaconDB.SaveAttestations(ctx, atts); err != nil {
return errors.Wrapf(err, "could not save block attestations from slot %d", b.Slot)
}
}
// Update justified check point.
if postState.CurrentJustifiedCheckpoint().Epoch > s.justifiedCheckpt.Epoch {
if err := s.updateJustified(ctx, postState); err != nil {
return err
}
// Save the latest block as head in cache.
if err := s.saveHeadNoDB(ctx, signed, blockRoot, postState); err != nil {
return err
}
// Rate limit how many blocks (2 epochs worth of blocks) a node keeps in the memory.
if len(s.getInitSyncBlocks()) > int(initialSyncBlockCacheSize) {
if uint64(len(s.getInitSyncBlocks())) > initialSyncBlockCacheSize {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return err
}
s.clearInitSyncBlocks()
}
if postState.CurrentJustifiedCheckpoint().Epoch > s.justifiedCheckpt.Epoch {
if err := s.updateJustifiedInitSync(ctx, postState.CurrentJustifiedCheckpoint()); err != nil {
return err
}
}
// Update finalized check point. Prune the block cache and helper caches on every new finalized epoch.
if postState.FinalizedCheckpointEpoch() > s.finalizedCheckpt.Epoch {
if featureconfig.Get().DisableNewStateMgmt {
startSlot := helpers.StartSlot(s.prevFinalizedCheckpt.Epoch)
endSlot := helpers.StartSlot(s.finalizedCheckpt.Epoch)
if endSlot > startSlot {
if err := s.rmStatesOlderThanLastFinalized(ctx, startSlot, endSlot); err != nil {
return errors.Wrapf(err, "could not delete states prior to finalized check point, range: %d, %d",
startSlot, endSlot)
}
}
if err := s.saveInitState(ctx, postState); err != nil {
return errors.Wrap(err, "could not save init sync finalized state")
}
}
if !featureconfig.Get().NoInitSyncBatchSaveBlocks {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return err
}
s.clearInitSyncBlocks()
}
if err := s.beaconDB.SaveFinalizedCheckpoint(ctx, postState.FinalizedCheckpoint()); err != nil {
return errors.Wrap(err, "could not save finalized checkpoint")
}
s.prevFinalizedCheckpt = s.finalizedCheckpt
s.finalizedCheckpt = postState.FinalizedCheckpoint()
if err := s.finalizedImpliesNewJustified(ctx, postState); err != nil {
return errors.Wrap(err, "could not save new justified")
}
if !featureconfig.Get().DisableNewStateMgmt {
fRoot := bytesutil.ToBytes32(postState.FinalizedCheckpoint().Root)
fBlock, err := s.beaconDB.Block(ctx, fRoot)
if err != nil {
return errors.Wrap(err, "could not get finalized block to migrate")
}
if err := s.stateGen.MigrateToCold(ctx, fBlock.Block.Slot, fRoot); err != nil {
return errors.Wrap(err, "could not migrate to cold")
}
if err := s.updateFinalized(ctx, postState.FinalizedCheckpoint()); err != nil {
return err
}
}
if featureconfig.Get().DisableNewStateMgmt {
numOfStates := len(s.boundaryRoots)
if numOfStates > initialSyncCacheSize {
if err = s.persistCachedStates(ctx, numOfStates); err != nil {
return err
return s.handleEpochBoundary(postState)
}
func (s *Service) onBlockBatch(ctx context.Context, blks []*ethpb.SignedBeaconBlock,
blockRoots [][32]byte) ([]*ethpb.Checkpoint, []*ethpb.Checkpoint, error) {
ctx, span := trace.StartSpan(ctx, "blockChain.onBlockBatch")
defer span.End()
if len(blks) == 0 || len(blockRoots) == 0 {
return nil, nil, errors.New("no blocks provided")
}
if blks[0] == nil || blks[0].Block == nil {
return nil, nil, errors.New("nil block")
}
b := blks[0].Block
// Retrieve incoming block's pre state.
if err := s.verifyBlkPreState(ctx, b); err != nil {
return nil, nil, err
}
preState, err := s.stateGen.StateByRootInitialSync(ctx, bytesutil.ToBytes32(b.ParentRoot))
if err != nil {
return nil, nil, err
}
if preState == nil {
return nil, nil, fmt.Errorf("nil pre state for slot %d", b.Slot)
}
jCheckpoints := make([]*ethpb.Checkpoint, len(blks))
fCheckpoints := make([]*ethpb.Checkpoint, len(blks))
sigSet := &bls.SignatureSet{
Signatures: []bls.Signature{},
PublicKeys: []bls.PublicKey{},
Messages: [][32]byte{},
}
set := new(bls.SignatureSet)
boundaries := make(map[[32]byte]*stateTrie.BeaconState)
for i, b := range blks {
set, preState, err = state.ExecuteStateTransitionNoVerifyAnySig(ctx, preState, b)
if err != nil {
return nil, nil, err
}
// Save potential boundary states.
if helpers.IsEpochStart(preState.Slot()) {
boundaries[blockRoots[i]] = preState.Copy()
if err := s.handleEpochBoundary(preState); err != nil {
return nil, nil, fmt.Errorf("could not handle epoch boundary state")
}
}
if len(s.initSyncState) > maxCacheSize {
s.pruneOldNonFinalizedStates()
jCheckpoints[i] = preState.CurrentJustifiedCheckpoint()
fCheckpoints[i] = preState.FinalizedCheckpoint()
sigSet.Join(set)
}
verify, err := bls.VerifyMultipleSignatures(sigSet.Signatures, sigSet.Messages, sigSet.PublicKeys)
if err != nil {
return nil, nil, err
}
if !verify {
return nil, nil, errors.New("batch block signature verification failed")
}
for r, st := range boundaries {
if err := s.stateGen.SaveState(ctx, r, st); err != nil {
return nil, nil, err
}
}
// Also saves the last post state which to be used as pre state for the next batch.
lastB := blks[len(blks)-1]
lastBR := blockRoots[len(blockRoots)-1]
if err := s.stateGen.SaveState(ctx, lastBR, preState); err != nil {
return nil, nil, err
}
if err := s.saveHeadNoDB(ctx, lastB, lastBR, preState); err != nil {
return nil, nil, err
}
return fCheckpoints, jCheckpoints, nil
}
// handles a block after the block's batch has been verified, where we can save blocks
// their state summaries and split them off to relative hot/cold storage.
func (s *Service) handleBlockAfterBatchVerify(ctx context.Context, signed *ethpb.SignedBeaconBlock,
blockRoot [32]byte, fCheckpoint *ethpb.Checkpoint, jCheckpoint *ethpb.Checkpoint) error {
b := signed.Block
s.saveInitSyncBlock(blockRoot, signed)
if err := s.insertBlockToForkChoiceStore(ctx, b, blockRoot, fCheckpoint, jCheckpoint); err != nil {
return err
}
s.stateGen.SaveStateSummary(ctx, signed, blockRoot)
// Rate limit how many blocks (2 epochs worth of blocks) a node keeps in the memory.
if uint64(len(s.getInitSyncBlocks())) > initialSyncBlockCacheSize {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return err
}
s.clearInitSyncBlocks()
}
if jCheckpoint.Epoch > s.justifiedCheckpt.Epoch {
if err := s.updateJustifiedInitSync(ctx, jCheckpoint); err != nil {
return err
}
}
// Epoch boundary bookkeeping such as logging epoch summaries.
// Update finalized check point. Prune the block cache and helper caches on every new finalized epoch.
if fCheckpoint.Epoch > s.finalizedCheckpt.Epoch {
if err := s.updateFinalized(ctx, fCheckpoint); err != nil {
return err
}
}
return nil
}
// Epoch boundary bookkeeping such as logging epoch summaries.
func (s *Service) handleEpochBoundary(postState *stateTrie.BeaconState) error {
if postState.Slot() >= s.nextEpochBoundarySlot {
reportEpochMetrics(postState)
s.nextEpochBoundarySlot = helpers.StartSlot(helpers.NextEpoch(postState))
@@ -337,32 +325,19 @@ func (s *Service) onBlockInitialSyncStateTransition(ctx context.Context, signed
if err := helpers.UpdateProposerIndicesInCache(postState, helpers.CurrentEpoch(postState)); err != nil {
return err
}
if featureconfig.Get().DisableNewStateMgmt && helpers.IsEpochStart(postState.Slot()) {
if err := s.beaconDB.SaveState(ctx, postState, root); err != nil {
return errors.Wrap(err, "could not save state")
}
}
}
return nil
}
// This feeds in the block and block's attestations to fork choice store. It's allows fork choice store
// to gain information on the most current chain.
func (s *Service) insertBlockToForkChoiceStore(ctx context.Context, blk *ethpb.BeaconBlock, root [32]byte, state *stateTrie.BeaconState) error {
if err := s.fillInForkChoiceMissingBlocks(ctx, blk, state); err != nil {
func (s *Service) insertBlockAndAttestationsToForkChoiceStore(ctx context.Context, blk *ethpb.BeaconBlock, root [32]byte,
state *stateTrie.BeaconState) error {
fCheckpoint := state.FinalizedCheckpoint()
jCheckpoint := state.CurrentJustifiedCheckpoint()
if err := s.insertBlockToForkChoiceStore(ctx, blk, root, fCheckpoint, jCheckpoint); err != nil {
return err
}
// Feed in block to fork choice store.
if err := s.forkChoiceStore.ProcessBlock(ctx,
blk.Slot, root, bytesutil.ToBytes32(blk.ParentRoot),
state.CurrentJustifiedCheckpoint().Epoch,
state.FinalizedCheckpointEpoch()); err != nil {
return errors.Wrap(err, "could not process block for proto array fork choice")
}
// Feed in block's attestations to fork choice store.
for _, a := range blk.Body.Attestations {
committee, err := helpers.BeaconCommitteeFromState(state, a.Data.Slot, a.Data.CommitteeIndex)
@@ -372,6 +347,41 @@ func (s *Service) insertBlockToForkChoiceStore(ctx context.Context, blk *ethpb.B
indices := attestationutil.AttestingIndices(a.AggregationBits, committee)
s.forkChoiceStore.ProcessAttestation(ctx, indices, bytesutil.ToBytes32(a.Data.BeaconBlockRoot), a.Data.Target.Epoch)
}
return nil
}
func (s *Service) insertBlockToForkChoiceStore(ctx context.Context, blk *ethpb.BeaconBlock,
root [32]byte, fCheckpoint *ethpb.Checkpoint, jCheckpoint *ethpb.Checkpoint) error {
if err := s.fillInForkChoiceMissingBlocks(ctx, blk, fCheckpoint, jCheckpoint); err != nil {
return err
}
// Feed in block to fork choice store.
if err := s.forkChoiceStore.ProcessBlock(ctx,
blk.Slot, root, bytesutil.ToBytes32(blk.ParentRoot), bytesutil.ToBytes32(blk.Body.Graffiti),
jCheckpoint.Epoch,
fCheckpoint.Epoch); err != nil {
return errors.Wrap(err, "could not process block for proto array fork choice")
}
return nil
}
// This saves post state info to DB or cache. This also saves post state info to fork choice store.
// Post state info consists of processed block and state. Do not call this method unless the block and state are verified.
func (s *Service) savePostStateInfo(ctx context.Context, r [32]byte, b *ethpb.SignedBeaconBlock, state *stateTrie.BeaconState, initSync bool) error {
ctx, span := trace.StartSpan(ctx, "blockChain.savePostStateInfo")
defer span.End()
if initSync {
s.saveInitSyncBlock(r, b)
} else {
if err := s.beaconDB.SaveBlock(ctx, b); err != nil {
return errors.Wrapf(err, "could not save block from slot %d", b.Block.Slot)
}
}
if err := s.stateGen.SaveState(ctx, r, state); err != nil {
return errors.Wrap(err, "could not save state")
}
if err := s.insertBlockAndAttestationsToForkChoiceStore(ctx, b.Block, r, state); err != nil {
return errors.Wrapf(err, "could not insert block %d to fork choice store", b.Block.Slot)
}
return nil
}

View File

@@ -7,12 +7,11 @@ import (
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/db/filters"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
"github.com/prysmaticlabs/prysm/shared/attestationutil"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/roughtime"
"github.com/prysmaticlabs/prysm/shared/traceutil"
@@ -33,22 +32,29 @@ func (s *Service) CurrentSlot() uint64 {
// to retrieve the state in DB. It verifies the pre state's validity and the incoming block
// is in the correct time window.
func (s *Service) getBlockPreState(ctx context.Context, b *ethpb.BeaconBlock) (*stateTrie.BeaconState, error) {
ctx, span := trace.StartSpan(ctx, "forkchoice.getBlockPreState")
ctx, span := trace.StartSpan(ctx, "forkChoice.getBlockPreState")
defer span.End()
// Verify incoming block has a valid pre state.
preState, err := s.verifyBlkPreState(ctx, b)
if err != nil {
if err := s.verifyBlkPreState(ctx, b); err != nil {
return nil, err
}
// Verify block slot time is not from the feature.
if err := helpers.VerifySlotTime(preState.GenesisTime(), b.Slot, helpers.TimeShiftTolerance); err != nil {
preState, err := s.stateGen.StateByRoot(ctx, bytesutil.ToBytes32(b.ParentRoot))
if err != nil {
return nil, errors.Wrapf(err, "could not get pre state for slot %d", b.Slot)
}
if preState == nil {
return nil, errors.Wrapf(err, "nil pre state for slot %d", b.Slot)
}
// Verify block slot time is not from the future.
if err := helpers.VerifySlotTime(preState.GenesisTime(), b.Slot, params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil {
return nil, err
}
// Verify block is a descendent of a finalized block.
if err := s.verifyBlkDescendant(ctx, bytesutil.ToBytes32(b.ParentRoot), b.Slot); err != nil {
if err := s.VerifyBlkDescendant(ctx, bytesutil.ToBytes32(b.ParentRoot)); err != nil {
return nil, err
}
@@ -61,87 +67,52 @@ func (s *Service) getBlockPreState(ctx context.Context, b *ethpb.BeaconBlock) (*
}
// verifyBlkPreState validates input block has a valid pre-state.
func (s *Service) verifyBlkPreState(ctx context.Context, b *ethpb.BeaconBlock) (*stateTrie.BeaconState, error) {
func (s *Service) verifyBlkPreState(ctx context.Context, b *ethpb.BeaconBlock) error {
ctx, span := trace.StartSpan(ctx, "chainService.verifyBlkPreState")
defer span.End()
if !featureconfig.Get().DisableNewStateMgmt {
parentRoot := bytesutil.ToBytes32(b.ParentRoot)
// Loosen the check to HasBlock because state summary gets saved in batches
// during initial syncing. There's no risk given a state summary object is just a
// a subset of the block object.
if !s.stateGen.StateSummaryExists(ctx, parentRoot) && !s.beaconDB.HasBlock(ctx, parentRoot) {
return nil, errors.New("could not reconstruct parent state")
}
if !s.stateGen.HasState(ctx, parentRoot) {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return nil, errors.Wrap(err, "could not save initial sync blocks")
}
s.clearInitSyncBlocks()
}
preState, err := s.stateGen.StateByRoot(ctx, parentRoot)
if err != nil {
return nil, errors.Wrapf(err, "could not get pre state for slot %d", b.Slot)
}
if preState == nil {
return nil, errors.Wrapf(err, "nil pre state for slot %d", b.Slot)
}
return preState, nil // No copy needed from newly hydrated state gen object.
parentRoot := bytesutil.ToBytes32(b.ParentRoot)
// Loosen the check to HasBlock because state summary gets saved in batches
// during initial syncing. There's no risk given a state summary object is just a
// a subset of the block object.
if !s.stateGen.StateSummaryExists(ctx, parentRoot) && !s.beaconDB.HasBlock(ctx, parentRoot) {
return errors.New("could not reconstruct parent state")
}
preState := s.initSyncState[bytesutil.ToBytes32(b.ParentRoot)]
var err error
if preState == nil {
if featureconfig.Get().CheckHeadState {
headRoot, err := s.HeadRoot(ctx)
if err != nil {
return nil, errors.Wrapf(err, "could not get head root")
}
if bytes.Equal(headRoot, b.ParentRoot) {
return s.HeadState(ctx)
}
if !s.stateGen.HasState(ctx, parentRoot) {
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return errors.Wrap(err, "could not save initial sync blocks")
}
preState, err = s.beaconDB.State(ctx, bytesutil.ToBytes32(b.ParentRoot))
if err != nil {
return nil, errors.Wrapf(err, "could not get pre state for slot %d", b.Slot)
}
if preState == nil {
if bytes.Equal(s.finalizedCheckpt.Root, b.ParentRoot) {
return nil, fmt.Errorf("pre state of slot %d does not exist", b.Slot)
}
preState, err = s.generateState(ctx, bytesutil.ToBytes32(s.finalizedCheckpt.Root), bytesutil.ToBytes32(b.ParentRoot))
if err != nil {
return nil, err
}
}
return preState, nil // No copy needed from newly hydrated DB object.
s.clearInitSyncBlocks()
}
return preState.Copy(), nil
return nil
}
// verifyBlkDescendant validates input block root is a descendant of the
// VerifyBlkDescendant validates input block root is a descendant of the
// current finalized block root.
func (s *Service) verifyBlkDescendant(ctx context.Context, root [32]byte, slot uint64) error {
ctx, span := trace.StartSpan(ctx, "forkchoice.verifyBlkDescendant")
func (s *Service) VerifyBlkDescendant(ctx context.Context, root [32]byte) error {
ctx, span := trace.StartSpan(ctx, "forkChoice.VerifyBlkDescendant")
defer span.End()
finalizedBlkSigned, err := s.beaconDB.Block(ctx, bytesutil.ToBytes32(s.finalizedCheckpt.Root))
if err != nil || finalizedBlkSigned == nil || finalizedBlkSigned.Block == nil {
return errors.Wrap(err, "could not get finalized block")
fRoot := s.ensureRootNotZeros(bytesutil.ToBytes32(s.finalizedCheckpt.Root))
finalizedBlkSigned, err := s.beaconDB.Block(ctx, fRoot)
if err != nil {
return err
}
if finalizedBlkSigned == nil || finalizedBlkSigned.Block == nil {
return errors.New("nil finalized block")
}
finalizedBlk := finalizedBlkSigned.Block
bFinalizedRoot, err := s.ancestor(ctx, root[:], finalizedBlk.Slot)
if err != nil {
return errors.Wrap(err, "could not get finalized block root")
}
if bFinalizedRoot == nil {
return fmt.Errorf("no finalized block known for block from slot %d", slot)
return fmt.Errorf("no finalized block known for block %#x", bytesutil.Trunc(root[:]))
}
if !bytes.Equal(bFinalizedRoot, s.finalizedCheckpt.Root) {
err := fmt.Errorf("block from slot %d is not a descendent of the current finalized block slot %d, %#x != %#x",
slot, finalizedBlk.Slot, bytesutil.Trunc(bFinalizedRoot), bytesutil.Trunc(s.finalizedCheckpt.Root))
if !bytes.Equal(bFinalizedRoot, fRoot[:]) {
err := fmt.Errorf("block %#x is not a descendent of the current finalized block slot %d, %#x != %#x",
bytesutil.Trunc(root[:]), finalizedBlk.Slot, bytesutil.Trunc(bFinalizedRoot),
bytesutil.Trunc(fRoot[:]))
traceutil.AnnotateError(span, err)
return err
}
@@ -158,64 +129,6 @@ func (s *Service) verifyBlkFinalizedSlot(b *ethpb.BeaconBlock) error {
return nil
}
// rmStatesOlderThanLastFinalized deletes the states in db since last finalized check point.
func (s *Service) rmStatesOlderThanLastFinalized(ctx context.Context, startSlot uint64, endSlot uint64) error {
ctx, span := trace.StartSpan(ctx, "forkchoice.rmStatesBySlots")
defer span.End()
// Make sure start slot is not a skipped slot
for i := startSlot; i > 0; i-- {
filter := filters.NewFilter().SetStartSlot(i).SetEndSlot(i)
b, err := s.beaconDB.Blocks(ctx, filter)
if err != nil {
return err
}
if len(b) > 0 {
startSlot = i
break
}
}
// Make sure finalized slot is not a skipped slot.
for i := endSlot; i > 0; i-- {
filter := filters.NewFilter().SetStartSlot(i).SetEndSlot(i)
b, err := s.beaconDB.Blocks(ctx, filter)
if err != nil {
return err
}
if len(b) > 0 {
endSlot = i - 1
break
}
}
// Do not remove genesis state
if startSlot == 0 {
startSlot++
}
// If end slot comes less than start slot
if endSlot < startSlot {
endSlot = startSlot
}
filter := filters.NewFilter().SetStartSlot(startSlot).SetEndSlot(endSlot)
roots, err := s.beaconDB.BlockRoots(ctx, filter)
if err != nil {
return err
}
roots, err = s.filterBlockRoots(ctx, roots)
if err != nil {
return err
}
if err := s.beaconDB.DeleteStates(ctx, roots); err != nil {
return err
}
return nil
}
// shouldUpdateCurrentJustified prevents bouncing attack, by only update conflicting justified
// checkpoints in the fork choice if in the early slots of the epoch.
// Otherwise, delay incorporation of new justified checkpoint until next epoch boundary.
@@ -225,9 +138,9 @@ func (s *Service) shouldUpdateCurrentJustified(ctx context.Context, newJustified
return true, nil
}
var newJustifiedBlockSigned *ethpb.SignedBeaconBlock
justifiedRoot := bytesutil.ToBytes32(newJustifiedCheckpt.Root)
justifiedRoot := s.ensureRootNotZeros(bytesutil.ToBytes32(newJustifiedCheckpt.Root))
var err error
if !featureconfig.Get().NoInitSyncBatchSaveBlocks && s.hasInitSyncBlock(justifiedRoot) {
if s.hasInitSyncBlock(justifiedRoot) {
newJustifiedBlockSigned = s.getInitSyncBlock(justifiedRoot)
} else {
newJustifiedBlockSigned, err = s.beaconDB.Block(ctx, justifiedRoot)
@@ -244,8 +157,8 @@ func (s *Service) shouldUpdateCurrentJustified(ctx context.Context, newJustified
return false, nil
}
var justifiedBlockSigned *ethpb.SignedBeaconBlock
cachedJustifiedRoot := bytesutil.ToBytes32(s.justifiedCheckpt.Root)
if !featureconfig.Get().NoInitSyncBatchSaveBlocks && s.hasInitSyncBlock(cachedJustifiedRoot) {
cachedJustifiedRoot := s.ensureRootNotZeros(bytesutil.ToBytes32(s.justifiedCheckpt.Root))
if s.hasInitSyncBlock(cachedJustifiedRoot) {
justifiedBlockSigned = s.getInitSyncBlock(cachedJustifiedRoot)
} else {
justifiedBlockSigned, err = s.beaconDB.Block(ctx, cachedJustifiedRoot)
@@ -258,7 +171,7 @@ func (s *Service) shouldUpdateCurrentJustified(ctx context.Context, newJustified
return false, errors.New("nil justified block")
}
justifiedBlock := justifiedBlockSigned.Block
b, err := s.ancestor(ctx, newJustifiedCheckpt.Root, justifiedBlock.Slot)
b, err := s.ancestor(ctx, justifiedRoot[:], justifiedBlock.Slot)
if err != nil {
return false, err
}
@@ -281,102 +194,60 @@ func (s *Service) updateJustified(ctx context.Context, state *stateTrie.BeaconSt
if canUpdate {
s.prevJustifiedCheckpt = s.justifiedCheckpt
s.justifiedCheckpt = cpt
}
if featureconfig.Get().DisableNewStateMgmt {
justifiedRoot := bytesutil.ToBytes32(cpt.Root)
justifiedState := s.initSyncState[justifiedRoot]
// If justified state is nil, resume back to normal syncing process and save
// justified check point.
var err error
if justifiedState == nil {
if s.beaconDB.HasState(ctx, justifiedRoot) {
return s.beaconDB.SaveJustifiedCheckpoint(ctx, cpt)
}
justifiedState, err = s.generateState(ctx, bytesutil.ToBytes32(s.finalizedCheckpt.Root), justifiedRoot)
if err != nil {
log.Error(err)
return s.beaconDB.SaveJustifiedCheckpoint(ctx, cpt)
}
}
if err := s.beaconDB.SaveState(ctx, justifiedState, justifiedRoot); err != nil {
return errors.Wrap(err, "could not save justified state")
if err := s.cacheJustifiedStateBalances(ctx, bytesutil.ToBytes32(s.justifiedCheckpt.Root)); err != nil {
return err
}
}
return s.beaconDB.SaveJustifiedCheckpoint(ctx, cpt)
}
// This saves every finalized state in DB during initial sync, needed as part of optimization to
// use cache state during initial sync in case of restart.
func (s *Service) saveInitState(ctx context.Context, state *stateTrie.BeaconState) error {
cpt := state.FinalizedCheckpoint()
finalizedRoot := bytesutil.ToBytes32(cpt.Root)
fs := s.initSyncState[finalizedRoot]
if fs == nil {
var err error
fs, err = s.beaconDB.State(ctx, finalizedRoot)
if err != nil {
return err
}
if fs == nil {
fs, err = s.generateState(ctx, bytesutil.ToBytes32(s.prevFinalizedCheckpt.Root), finalizedRoot)
if err != nil {
// This might happen if the client was in sync and is now re-syncing for whatever reason.
log.Warn("Initial sync cache did not have finalized state root cached")
return err
}
}
// This caches input checkpoint as justified for the service struct. It rotates current justified to previous justified,
// caches justified checkpoint balances for fork choice and save justified checkpoint in DB.
// This method does not have defense against fork choice bouncing attack, which is why it's only recommend to be used during initial syncing.
func (s *Service) updateJustifiedInitSync(ctx context.Context, cp *ethpb.Checkpoint) error {
s.prevJustifiedCheckpt = s.justifiedCheckpt
s.justifiedCheckpt = cp
if err := s.cacheJustifiedStateBalances(ctx, bytesutil.ToBytes32(s.justifiedCheckpt.Root)); err != nil {
return err
}
if err := s.beaconDB.SaveState(ctx, fs, finalizedRoot); err != nil {
return errors.Wrap(err, "could not save state")
}
return nil
return s.beaconDB.SaveJustifiedCheckpoint(ctx, cp)
}
// This filters block roots that are not known as head root and finalized root in DB.
// It serves as the last line of defence before we prune states.
func (s *Service) filterBlockRoots(ctx context.Context, roots [][32]byte) ([][32]byte, error) {
f, err := s.beaconDB.FinalizedCheckpoint(ctx)
if err != nil {
return nil, err
func (s *Service) updateFinalized(ctx context.Context, cp *ethpb.Checkpoint) error {
// Blocks need to be saved so that we can retrieve finalized block from
// DB when migrating states.
if err := s.beaconDB.SaveBlocks(ctx, s.getInitSyncBlocks()); err != nil {
return err
}
fRoot := f.Root
h, err := s.beaconDB.HeadBlock(ctx)
if err != nil {
return nil, err
}
hRoot, err := ssz.HashTreeRoot(h.Block)
if err != nil {
return nil, err
s.clearInitSyncBlocks()
s.prevFinalizedCheckpt = s.finalizedCheckpt
s.finalizedCheckpt = cp
fRoot := bytesutil.ToBytes32(cp.Root)
if err := s.stateGen.MigrateToCold(ctx, fRoot); err != nil {
return errors.Wrap(err, "could not migrate to cold")
}
filtered := make([][32]byte, 0, len(roots))
for _, root := range roots {
if bytes.Equal(root[:], fRoot[:]) || bytes.Equal(root[:], hRoot[:]) {
continue
}
filtered = append(filtered, root)
}
return filtered, nil
return s.beaconDB.SaveFinalizedCheckpoint(ctx, cp)
}
// ancestor returns the block root of an ancestry block from the input block root.
//
// Spec pseudocode definition:
// def get_ancestor(store: Store, root: Hash, slot: Slot) -> Hash:
// def get_ancestor(store: Store, root: Root, slot: Slot) -> Root:
// block = store.blocks[root]
// if block.slot > slot:
// return get_ancestor(store, block.parent_root, slot)
// return get_ancestor(store, block.parent_root, slot)
// elif block.slot == slot:
// return root
// return root
// else:
// return Bytes32() # root is older than queried slot: no results.
// # root is older than queried slot, thus a skip slot. Return most recent root prior to slot
// return root
func (s *Service) ancestor(ctx context.Context, root []byte, slot uint64) ([]byte, error) {
ctx, span := trace.StartSpan(ctx, "forkchoice.ancestor")
ctx, span := trace.StartSpan(ctx, "forkChoice.ancestor")
defer span.End()
// Stop recursive ancestry lookup if context is cancelled.
@@ -384,27 +255,27 @@ func (s *Service) ancestor(ctx context.Context, root []byte, slot uint64) ([]byt
return nil, ctx.Err()
}
signed, err := s.beaconDB.Block(ctx, bytesutil.ToBytes32(root))
r := bytesutil.ToBytes32(root)
// Get ancestor root from fork choice store instead of recursively looking up blocks in DB.
// This is most optimal outcome.
if s.forkChoiceStore.HasParent(r) {
return s.forkChoiceStore.AncestorRoot(ctx, r, slot)
}
signed, err := s.beaconDB.Block(ctx, r)
if err != nil {
return nil, errors.Wrap(err, "could not get ancestor block")
}
if !featureconfig.Get().NoInitSyncBatchSaveBlocks && s.hasInitSyncBlock(bytesutil.ToBytes32(root)) {
signed = s.getInitSyncBlock(bytesutil.ToBytes32(root))
if s.hasInitSyncBlock(r) {
signed = s.getInitSyncBlock(r)
}
if signed == nil || signed.Block == nil {
return nil, errors.New("nil block")
}
b := signed.Block
// If we dont have the ancestor in the DB, simply return nil so rest of fork choice
// operation can proceed. This is not an error condition.
if b == nil || b.Slot < slot {
return nil, nil
}
if b.Slot == slot {
if b.Slot == slot || b.Slot < slot {
return root, nil
}
@@ -415,34 +286,49 @@ func (s *Service) ancestor(ctx context.Context, root []byte, slot uint64) ([]byt
// the store's justified is not in chain with finalized check point.
//
// Spec definition:
// if (
// state.current_justified_checkpoint.epoch > store.justified_checkpoint.epoch
// or get_ancestor(store, store.justified_checkpoint.root, finalized_slot) != store.finalized_checkpoint.root
// ):
// store.justified_checkpoint = state.current_justified_checkpoint
// # Potentially update justified if different from store
// if store.justified_checkpoint != state.current_justified_checkpoint:
// # Update justified if new justified is later than store justified
// if state.current_justified_checkpoint.epoch > store.justified_checkpoint.epoch:
// store.justified_checkpoint = state.current_justified_checkpoint
// return
// # Update justified if store justified is not in chain with finalized checkpoint
// finalized_slot = compute_start_slot_at_epoch(store.finalized_checkpoint.epoch)
// ancestor_at_finalized_slot = get_ancestor(store, store.justified_checkpoint.root, finalized_slot)
// if ancestor_at_finalized_slot != store.finalized_checkpoint.root:
// store.justified_checkpoint = state.current_justified_checkpoint
func (s *Service) finalizedImpliesNewJustified(ctx context.Context, state *stateTrie.BeaconState) error {
finalizedBlkSigned, err := s.beaconDB.Block(ctx, bytesutil.ToBytes32(s.finalizedCheckpt.Root))
if err != nil || finalizedBlkSigned == nil || finalizedBlkSigned.Block == nil {
return errors.Wrap(err, "could not get finalized block")
}
finalizedBlk := finalizedBlkSigned.Block
// Update justified if it's different than the one cached in the store.
if !attestationutil.CheckPointIsEqual(s.justifiedCheckpt, state.CurrentJustifiedCheckpoint()) {
if state.CurrentJustifiedCheckpoint().Epoch > s.justifiedCheckpt.Epoch {
s.justifiedCheckpt = state.CurrentJustifiedCheckpoint()
if err := s.cacheJustifiedStateBalances(ctx, bytesutil.ToBytes32(s.justifiedCheckpt.Root)); err != nil {
return err
}
return nil
}
anc, err := s.ancestor(ctx, s.justifiedCheckpt.Root, finalizedBlk.Slot)
if err != nil {
return err
// Update justified if store justified is not in chain with finalized check point.
finalizedSlot := helpers.StartSlot(s.finalizedCheckpt.Epoch)
justifiedRoot := s.ensureRootNotZeros(bytesutil.ToBytes32(s.justifiedCheckpt.Root))
anc, err := s.ancestor(ctx, justifiedRoot[:], finalizedSlot)
if err != nil {
return err
}
if !bytes.Equal(anc, s.finalizedCheckpt.Root) {
s.justifiedCheckpt = state.CurrentJustifiedCheckpoint()
if err := s.cacheJustifiedStateBalances(ctx, bytesutil.ToBytes32(s.justifiedCheckpt.Root)); err != nil {
return err
}
}
}
// Either the new justified is later than stored justified or not in chain with finalized check pint.
if cpt := state.CurrentJustifiedCheckpoint(); cpt != nil && cpt.Epoch > s.justifiedCheckpt.Epoch || !bytes.Equal(anc, s.finalizedCheckpt.Root) {
s.justifiedCheckpt = state.CurrentJustifiedCheckpoint()
}
return nil
}
// This retrieves missing blocks from DB (ie. the blocks that couldn't received over sync) and inserts them to fork choice store.
// This retrieves missing blocks from DB (ie. the blocks that couldn't be received over sync) and inserts them to fork choice store.
// This is useful for block tree visualizer and additional vote accounting.
func (s *Service) fillInForkChoiceMissingBlocks(ctx context.Context, blk *ethpb.BeaconBlock, state *stateTrie.BeaconState) error {
func (s *Service) fillInForkChoiceMissingBlocks(ctx context.Context, blk *ethpb.BeaconBlock,
fCheckpoint *ethpb.Checkpoint, jCheckpoint *ethpb.Checkpoint) error {
pendingNodes := make([]*ethpb.BeaconBlock, 0)
parentRoot := bytesutil.ToBytes32(blk.ParentRoot)
@@ -466,15 +352,15 @@ func (s *Service) fillInForkChoiceMissingBlocks(ctx context.Context, blk *ethpb.
// Lower slots should be at the end of the list.
for i := len(pendingNodes) - 1; i >= 0; i-- {
b := pendingNodes[i]
r, err := ssz.HashTreeRoot(b)
r, err := stateutil.BlockRoot(b)
if err != nil {
return err
}
if err := s.forkChoiceStore.ProcessBlock(ctx,
b.Slot, r, bytesutil.ToBytes32(b.ParentRoot),
state.CurrentJustifiedCheckpoint().Epoch,
state.FinalizedCheckpointEpoch()); err != nil {
b.Slot, r, bytesutil.ToBytes32(b.ParentRoot), bytesutil.ToBytes32(b.Body.Graffiti),
jCheckpoint.Epoch,
fCheckpoint.Epoch); err != nil {
return errors.Wrap(err, "could not process block for proto array fork choice")
}
}
@@ -498,3 +384,12 @@ func (s *Service) deletePoolAtts(atts []*ethpb.Attestation) error {
return nil
}
// This ensures that the input root defaults to using genesis root instead of zero hashes. This is needed for handling
// fork choice justification routine.
func (s *Service) ensureRootNotZeros(root [32]byte) [32]byte {
if root == params.BeaconConfig().ZeroHash {
return s.genesisRoot
}
return root
}

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,7 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
@@ -22,9 +23,10 @@ import (
type AttestationReceiver interface {
ReceiveAttestationNoPubsub(ctx context.Context, att *ethpb.Attestation) error
IsValidAttestation(ctx context.Context, att *ethpb.Attestation) bool
AttestationPreState(ctx context.Context, att *ethpb.Attestation) (*state.BeaconState, error)
}
// ReceiveAttestationNoPubsub is a function that defines the operations that are preformed on
// ReceiveAttestationNoPubsub is a function that defines the operations that are performed on
// attestation that is received from regular sync. The operations consist of:
// 1. Validate attestation, update validator's latest vote
// 2. Apply fork choice to the processed attestation
@@ -39,15 +41,10 @@ func (s *Service) ReceiveAttestationNoPubsub(ctx context.Context, att *ethpb.Att
}
if !featureconfig.Get().DisableUpdateHeadPerAttestation {
baseState, err := s.getAttPreState(ctx, att.Data.Target)
if err != nil {
return err
}
// This updates fork choice head, if a new head could not be updated due to
// long range or intermediate forking. It simply logs a warning and returns nil
// as that's more appropriate than returning errors.
if err := s.updateHead(ctx, baseState.Balances()); err != nil {
if err := s.updateHead(ctx, s.getJustifiedBalances()); err != nil {
log.Warnf("Resolving fork due to new attestation: %v", err)
return nil
}
@@ -58,9 +55,9 @@ func (s *Service) ReceiveAttestationNoPubsub(ctx context.Context, att *ethpb.Att
// IsValidAttestation returns true if the attestation can be verified against its pre-state.
func (s *Service) IsValidAttestation(ctx context.Context, att *ethpb.Attestation) bool {
baseState, err := s.getAttPreState(ctx, att.Data.Target)
baseState, err := s.AttestationPreState(ctx, att)
if err != nil {
log.WithError(err).Error("Failed to validate attestation")
log.WithError(err).Error("Failed to get attestation pre state")
return false
}
@@ -72,6 +69,11 @@ func (s *Service) IsValidAttestation(ctx context.Context, att *ethpb.Attestation
return true
}
// AttestationPreState returns the pre state of attestation.
func (s *Service) AttestationPreState(ctx context.Context, att *ethpb.Attestation) (*state.BeaconState, error) {
return s.getAttPreState(ctx, att.Data.Target)
}
// This processes attestations from the attestation pool to account for validator votes and fork choice.
func (s *Service) processAttestation(subscribedToStateEvents chan struct{}) {
// Wait for state to be initialized.
@@ -90,13 +92,15 @@ func (s *Service) processAttestation(subscribedToStateEvents chan struct{}) {
ctx := context.Background()
atts := s.attPool.ForkchoiceAttestations()
for _, a := range atts {
var hasState bool
if !featureconfig.Get().DisableNewStateMgmt {
hasState = s.stateGen.StateSummaryExists(ctx, bytesutil.ToBytes32(a.Data.BeaconBlockRoot))
} else {
hasState = s.beaconDB.HasState(ctx, bytesutil.ToBytes32(a.Data.BeaconBlockRoot)) && s.beaconDB.HasState(ctx, bytesutil.ToBytes32(a.Data.Target.Root))
// Based on the spec, don't process the attestation until the subsequent slot.
// This delays consideration in the fork choice until their slot is in the past.
// https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/fork-choice.md#validate_on_attestation
nextSlot := a.Data.Slot + 1
if err := helpers.VerifySlotTime(uint64(s.genesisTime.Unix()), nextSlot, params.BeaconNetworkConfig().MaximumGossipClockDisparity); err != nil {
continue
}
hasState := s.stateGen.StateSummaryExists(ctx, bytesutil.ToBytes32(a.Data.BeaconBlockRoot))
hasBlock := s.hasBlock(ctx, bytesutil.ToBytes32(a.Data.BeaconBlockRoot))
if !(hasState && hasBlock) {
continue

View File

@@ -5,21 +5,18 @@ import (
"time"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
)
func TestVerifyCheckpointEpoch_Ok(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
helpers.ClearCache()
db, sc := testDB.SetupDB(t)
chainService := setupBeaconChain(t, db)
chainService := setupBeaconChain(t, db, sc)
chainService.genesisTime = time.Now()
if !chainService.verifyCheckpointEpoch(&ethpb.Checkpoint{}) {
t.Error("Wanted true, got false")
}
if chainService.verifyCheckpointEpoch(&ethpb.Checkpoint{Epoch: 1}) {
t.Error("Wanted false, got true")
}
assert.Equal(t, true, chainService.verifyCheckpointEpoch(&ethpb.Checkpoint{}))
assert.Equal(t, false, chainService.verifyCheckpointEpoch(&ethpb.Checkpoint{Epoch: 1}))
}

View File

@@ -1,20 +1,13 @@
package blockchain
import (
"bytes"
"context"
"encoding/hex"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/traceutil"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
@@ -22,87 +15,32 @@ import (
// BlockReceiver interface defines the methods of chain service receive and processing new blocks.
type BlockReceiver interface {
ReceiveBlock(ctx context.Context, block *ethpb.SignedBeaconBlock) error
ReceiveBlockNoPubsub(ctx context.Context, block *ethpb.SignedBeaconBlock) error
ReceiveBlockNoPubsubForkchoice(ctx context.Context, block *ethpb.SignedBeaconBlock) error
ReceiveBlockNoVerify(ctx context.Context, block *ethpb.SignedBeaconBlock) error
ReceiveBlock(ctx context.Context, block *ethpb.SignedBeaconBlock, blockRoot [32]byte) error
ReceiveBlockInitialSync(ctx context.Context, block *ethpb.SignedBeaconBlock, blockRoot [32]byte) error
ReceiveBlockBatch(ctx context.Context, blocks []*ethpb.SignedBeaconBlock, blkRoots [][32]byte) error
HasInitSyncBlock(root [32]byte) bool
}
// ReceiveBlock is a function that defines the operations that are preformed on
// blocks that is received from rpc service. The operations consists of:
// 1. Gossip block to other peers
// 2. Validate block, apply state transition and update check points
// 3. Apply fork choice to the processed block
// 4. Save latest head info
func (s *Service) ReceiveBlock(ctx context.Context, block *ethpb.SignedBeaconBlock) error {
ctx, span := trace.StartSpan(ctx, "beacon-chain.blockchain.ReceiveBlock")
defer span.End()
root, err := ssz.HashTreeRoot(block.Block)
if err != nil {
return errors.Wrap(err, "could not get signing root on received block")
}
// Broadcast the new block to the network.
if err := s.p2p.Broadcast(ctx, block); err != nil {
return errors.Wrap(err, "could not broadcast block")
}
log.WithFields(logrus.Fields{
"blockRoot": hex.EncodeToString(root[:]),
}).Debug("Broadcasting block")
if err := s.ReceiveBlockNoPubsub(ctx, block); err != nil {
return err
}
return nil
}
// ReceiveBlockNoPubsub is a function that defines the the operations (minus pubsub)
// that are preformed on blocks that is received from regular sync service. The operations consists of:
// ReceiveBlock is a function that defines the the operations (minus pubsub)
// that are performed on blocks that is received from regular sync service. The operations consists of:
// 1. Validate block, apply state transition and update check points
// 2. Apply fork choice to the processed block
// 3. Save latest head info
func (s *Service) ReceiveBlockNoPubsub(ctx context.Context, block *ethpb.SignedBeaconBlock) error {
ctx, span := trace.StartSpan(ctx, "beacon-chain.blockchain.ReceiveBlockNoPubsub")
func (s *Service) ReceiveBlock(ctx context.Context, block *ethpb.SignedBeaconBlock, blockRoot [32]byte) error {
ctx, span := trace.StartSpan(ctx, "blockChain.ReceiveBlock")
defer span.End()
blockCopy := stateTrie.CopySignedBeaconBlock(block)
// Apply state transition on the new block.
postState, err := s.onBlock(ctx, blockCopy)
if err != nil {
if err := s.onBlock(ctx, blockCopy, blockRoot); err != nil {
err := errors.Wrap(err, "could not process block")
traceutil.AnnotateError(span, err)
return err
}
// Add attestations from the block to the pool for fork choice.
if err := s.attPool.SaveBlockAttestations(blockCopy.Block.Body.Attestations); err != nil {
log.Errorf("Could not save attestation for fork choice: %v", err)
return nil
}
for _, exit := range block.Block.Body.VoluntaryExits {
s.exitPool.MarkIncluded(exit)
}
s.epochParticipationLock.Lock()
defer s.epochParticipationLock.Unlock()
s.epochParticipation[helpers.SlotToEpoch(blockCopy.Block.Slot)] = precompute.Balances
root, err := stateutil.BlockRoot(blockCopy.Block)
if err != nil {
return errors.Wrap(err, "could not get signing root on received block")
}
if featureconfig.Get().DisableForkChoice && block.Block.Slot > s.headSlot() {
if err := s.saveHead(ctx, root); err != nil {
return errors.Wrap(err, "could not save head")
}
} else {
if err := s.updateHead(ctx, postState.Balances()); err != nil {
return errors.Wrap(err, "could not save head")
}
// Update and save head block after fork choice.
if err := s.updateHead(ctx, s.getJustifiedBalances()); err != nil {
return errors.Wrap(err, "could not update head")
}
// Send notification of the processed block to the state feed.
@@ -110,13 +48,21 @@ func (s *Service) ReceiveBlockNoPubsub(ctx context.Context, block *ethpb.SignedB
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
Slot: blockCopy.Block.Slot,
BlockRoot: root,
BlockRoot: blockRoot,
Verified: true,
},
})
// Handle post block operations such as attestations and exits.
if err := s.handlePostBlockOperations(blockCopy.Block); err != nil {
return err
}
// Reports on block and fork choice metrics.
reportSlotMetrics(blockCopy.Block.Slot, s.headSlot(), s.finalizedCheckpt)
reportSlotMetrics(blockCopy.Block.Slot, s.headSlot(), s.CurrentSlot(), s.finalizedCheckpt)
// Log block sync status.
logBlockSyncStatus(blockCopy.Block, blockRoot, s.finalizedCheckpt)
// Log state transition data.
logStateTransitionData(blockCopy.Block)
@@ -124,105 +70,32 @@ func (s *Service) ReceiveBlockNoPubsub(ctx context.Context, block *ethpb.SignedB
return nil
}
// ReceiveBlockNoPubsubForkchoice is a function that defines the all operations (minus pubsub and forkchoice)
// that are preformed blocks that is received from initial sync service. The operations consists of:
// 1. Validate block, apply state transition and update check points
// 2. Save latest head info
func (s *Service) ReceiveBlockNoPubsubForkchoice(ctx context.Context, block *ethpb.SignedBeaconBlock) error {
ctx, span := trace.StartSpan(ctx, "beacon-chain.blockchain.ReceiveBlockNoForkchoice")
// ReceiveBlockInitialSync processes the input block for the purpose of initial syncing.
// This method should only be used on blocks during initial syncing phase.
func (s *Service) ReceiveBlockInitialSync(ctx context.Context, block *ethpb.SignedBeaconBlock, blockRoot [32]byte) error {
ctx, span := trace.StartSpan(ctx, "blockChain.ReceiveBlockNoVerify")
defer span.End()
blockCopy := stateTrie.CopySignedBeaconBlock(block)
// Apply state transition on the new block.
_, err := s.onBlock(ctx, blockCopy)
if err != nil {
if err := s.onBlockInitialSyncStateTransition(ctx, blockCopy, blockRoot); err != nil {
err := errors.Wrap(err, "could not process block")
traceutil.AnnotateError(span, err)
return err
}
root, err := stateutil.BlockRoot(blockCopy.Block)
if err != nil {
return errors.Wrap(err, "could not get signing root on received block")
}
cachedHeadRoot, err := s.HeadRoot(ctx)
if err != nil {
return errors.Wrap(err, "could not get head root from cache")
}
if !bytes.Equal(root[:], cachedHeadRoot) {
if err := s.saveHead(ctx, root); err != nil {
return errors.Wrap(err, "could not save head")
}
}
// Send notification of the processed block to the state feed.
s.stateNotifier.StateFeed().Send(&feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
Slot: blockCopy.Block.Slot,
BlockRoot: root,
BlockRoot: blockRoot,
Verified: true,
},
})
// Reports on block and fork choice metrics.
reportSlotMetrics(blockCopy.Block.Slot, s.headSlot(), s.finalizedCheckpt)
// Log state transition data.
logStateTransitionData(blockCopy.Block)
s.epochParticipationLock.Lock()
defer s.epochParticipationLock.Unlock()
s.epochParticipation[helpers.SlotToEpoch(blockCopy.Block.Slot)] = precompute.Balances
return nil
}
// ReceiveBlockNoVerify runs state transition on a input block without verifying the block's BLS contents.
// Depends on the security model, this is the "minimal" work a node can do to sync the chain.
// It simulates light client behavior and assumes 100% trust with the syncing peer.
func (s *Service) ReceiveBlockNoVerify(ctx context.Context, block *ethpb.SignedBeaconBlock) error {
ctx, span := trace.StartSpan(ctx, "beacon-chain.blockchain.ReceiveBlockNoVerify")
defer span.End()
blockCopy := stateTrie.CopySignedBeaconBlock(block)
// Apply state transition on the incoming newly received blockCopy without verifying its BLS contents.
if err := s.onBlockInitialSyncStateTransition(ctx, blockCopy); err != nil {
err := errors.Wrap(err, "could not process block")
traceutil.AnnotateError(span, err)
return err
}
root, err := stateutil.BlockRoot(blockCopy.Block)
if err != nil {
return errors.Wrap(err, "could not get signing root on received blockCopy")
}
cachedHeadRoot, err := s.HeadRoot(ctx)
if err != nil {
return errors.Wrap(err, "could not get head root from cache")
}
if !bytes.Equal(root[:], cachedHeadRoot) {
if err := s.saveHeadNoDB(ctx, blockCopy, root); err != nil {
err := errors.Wrap(err, "could not save head")
traceutil.AnnotateError(span, err)
return err
}
}
// Send notification of the processed block to the state feed.
s.stateNotifier.StateFeed().Send(&feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
Slot: blockCopy.Block.Slot,
BlockRoot: root,
Verified: false,
},
})
// Reports on blockCopy and fork choice metrics.
reportSlotMetrics(blockCopy.Block.Slot, s.headSlot(), s.finalizedCheckpt)
reportSlotMetrics(blockCopy.Block.Slot, s.headSlot(), s.CurrentSlot(), s.finalizedCheckpt)
// Log state transition data.
log.WithFields(logrus.Fields{
@@ -231,9 +104,43 @@ func (s *Service) ReceiveBlockNoVerify(ctx context.Context, block *ethpb.SignedB
"deposits": len(blockCopy.Block.Body.Deposits),
}).Debug("Finished applying state transition")
s.epochParticipationLock.Lock()
defer s.epochParticipationLock.Unlock()
s.epochParticipation[helpers.SlotToEpoch(blockCopy.Block.Slot)] = precompute.Balances
return nil
}
// ReceiveBlockBatch processes the whole block batch at once, assuming the block batch is linear ,transitioning
// the state, performing batch verification of all collected signatures and then performing the appropriate
// actions for a block post-transition.
func (s *Service) ReceiveBlockBatch(ctx context.Context, blocks []*ethpb.SignedBeaconBlock, blkRoots [][32]byte) error {
ctx, span := trace.StartSpan(ctx, "blockChain.ReceiveBlockBatch")
defer span.End()
// Apply state transition on the incoming newly received blockCopy without verifying its BLS contents.
fCheckpoints, jCheckpoints, err := s.onBlockBatch(ctx, blocks, blkRoots)
if err != nil {
err := errors.Wrap(err, "could not process block in batch")
traceutil.AnnotateError(span, err)
return err
}
for i, b := range blocks {
blockCopy := stateTrie.CopySignedBeaconBlock(b)
if err = s.handleBlockAfterBatchVerify(ctx, blockCopy, blkRoots[i], fCheckpoints[i], jCheckpoints[i]); err != nil {
traceutil.AnnotateError(span, err)
return err
}
// Send notification of the processed block to the state feed.
s.stateNotifier.StateFeed().Send(&feed.Event{
Type: statefeed.BlockProcessed,
Data: &statefeed.BlockProcessedData{
Slot: blockCopy.Block.Slot,
BlockRoot: blkRoots[i],
Verified: true,
},
})
// Reports on blockCopy and fork choice metrics.
reportSlotMetrics(blockCopy.Block.Slot, s.headSlot(), s.CurrentSlot(), s.finalizedCheckpt)
}
return nil
}
@@ -242,3 +149,26 @@ func (s *Service) ReceiveBlockNoVerify(ctx context.Context, block *ethpb.SignedB
func (s *Service) HasInitSyncBlock(root [32]byte) bool {
return s.hasInitSyncBlock(root)
}
func (s *Service) handlePostBlockOperations(b *ethpb.BeaconBlock) error {
// Delete the processed block attestations from attestation pool.
if err := s.deletePoolAtts(b.Body.Attestations); err != nil {
return err
}
// Add block attestations to the fork choice pool to compute head.
if err := s.attPool.SaveBlockAttestations(b.Body.Attestations); err != nil {
log.Errorf("Could not save block attestations for fork choice: %v", err)
return nil
}
// Mark block exits as seen so we don't include same ones in future blocks.
for _, e := range b.Body.VoluntaryExits {
s.exitPool.MarkIncluded(e)
}
// Mark attester slashings as seen so we don't include same ones in future blocks.
for _, as := range b.Body.AttesterSlashings {
s.slashingPool.MarkIncludedAttesterSlashing(as)
}
return nil
}

View File

@@ -0,0 +1,370 @@
package blockchain
import (
"context"
"sync"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
blockchainTesting "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
"github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations"
"github.com/prysmaticlabs/prysm/beacon-chain/operations/voluntaryexits"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestService_ReceiveBlock(t *testing.T) {
ctx := context.Background()
genesis, keys := testutil.DeterministicGenesisState(t, 64)
genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock {
blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot)
assert.NoError(t, err)
return blk
}
bc := params.BeaconConfig()
bc.ShardCommitteePeriod = 0 // Required for voluntary exits test in reasonable time.
params.OverrideBeaconConfig(bc)
type args struct {
block *ethpb.SignedBeaconBlock
}
tests := []struct {
name string
args args
wantErr bool
check func(*testing.T, *Service)
}{
{
name: "applies block with state transition",
args: args{
block: genFullBlock(t, testutil.DefaultBlockGenConfig(), 2 /*slot*/),
},
check: func(t *testing.T, s *Service) {
if hs := s.head.state.Slot(); hs != 2 {
t.Errorf("Unexpected state slot. Got %d but wanted %d", hs, 2)
}
if bs := s.head.block.Block.Slot; bs != 2 {
t.Errorf("Unexpected head block slot. Got %d but wanted %d", bs, 2)
}
},
},
{
name: "saves attestations to pool",
args: args{
block: genFullBlock(t,
&testutil.BlockGenConfig{
NumProposerSlashings: 0,
NumAttesterSlashings: 0,
NumAttestations: 2,
NumDeposits: 0,
NumVoluntaryExits: 0,
},
1, /*slot*/
),
},
check: func(t *testing.T, s *Service) {
if baCount := len(s.attPool.BlockAttestations()); baCount != 2 {
t.Errorf("Did not get the correct number of block attestations saved to the pool. "+
"Got %d but wanted %d", baCount, 2)
}
},
},
{
name: "updates exit pool",
args: args{
block: genFullBlock(t, &testutil.BlockGenConfig{
NumProposerSlashings: 0,
NumAttesterSlashings: 0,
NumAttestations: 0,
NumDeposits: 0,
NumVoluntaryExits: 3,
},
1, /*slot*/
),
},
check: func(t *testing.T, s *Service) {
var n int
for i := uint64(0); int(i) < genesis.NumValidators(); i++ {
if s.exitPool.HasBeenIncluded(i) {
n++
}
}
if n != 3 {
t.Errorf("Did not mark the correct number of exits. Got %d but wanted %d", n, 3)
}
},
},
{
name: "notifies block processed on state feed",
args: args{
block: genFullBlock(t, testutil.DefaultBlockGenConfig(), 1 /*slot*/),
},
check: func(t *testing.T, s *Service) {
if recvd := len(s.stateNotifier.(*blockchainTesting.MockStateNotifier).ReceivedEvents()); recvd < 1 {
t.Errorf("Received %d state notifications, expected at least 1", recvd)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
db, stateSummaryCache := testDB.SetupDB(t)
genesisBlockRoot := bytesutil.ToBytes32(nil)
require.NoError(t, db.SaveState(ctx, genesis, genesisBlockRoot))
cfg := &Config{
BeaconDB: db,
ForkChoiceStore: protoarray.New(
0, // justifiedEpoch
0, // finalizedEpoch
genesisBlockRoot,
),
AttPool: attestations.NewPool(),
ExitPool: voluntaryexits.NewPool(),
StateNotifier: &blockchainTesting.MockStateNotifier{RecordEvents: true},
StateGen: stategen.New(db, stateSummaryCache),
}
s, err := NewService(ctx, cfg)
require.NoError(t, err)
require.NoError(t, s.saveGenesisData(ctx, genesis))
gBlk, err := s.beaconDB.GenesisBlock(ctx)
require.NoError(t, err)
gRoot, err := stateutil.BlockRoot(gBlk.Block)
s.finalizedCheckpt = &ethpb.Checkpoint{Root: gRoot[:]}
root, err := stateutil.BlockRoot(tt.args.block.Block)
require.NoError(t, err)
if err := s.ReceiveBlock(ctx, tt.args.block, root); (err != nil) != tt.wantErr {
t.Errorf("ReceiveBlock() error = %v, wantErr %v", err, tt.wantErr)
} else {
tt.check(t, s)
}
})
}
}
func TestService_ReceiveBlockUpdateHead(t *testing.T) {
ctx := context.Background()
genesis, keys := testutil.DeterministicGenesisState(t, 64)
b, err := testutil.GenerateFullBlock(genesis, keys, testutil.DefaultBlockGenConfig(), 1)
assert.NoError(t, err)
db, stateSummaryCache := testDB.SetupDB(t)
genesisBlockRoot := bytesutil.ToBytes32(nil)
require.NoError(t, db.SaveState(ctx, genesis, genesisBlockRoot))
cfg := &Config{
BeaconDB: db,
ForkChoiceStore: protoarray.New(
0, // justifiedEpoch
0, // finalizedEpoch
genesisBlockRoot,
),
AttPool: attestations.NewPool(),
ExitPool: voluntaryexits.NewPool(),
StateNotifier: &blockchainTesting.MockStateNotifier{RecordEvents: true},
StateGen: stategen.New(db, stateSummaryCache),
}
s, err := NewService(ctx, cfg)
require.NoError(t, err)
require.NoError(t, s.saveGenesisData(ctx, genesis))
gBlk, err := s.beaconDB.GenesisBlock(ctx)
require.NoError(t, err)
gRoot, err := stateutil.BlockRoot(gBlk.Block)
s.finalizedCheckpt = &ethpb.Checkpoint{Root: gRoot[:]}
root, err := stateutil.BlockRoot(b.Block)
require.NoError(t, err)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
require.NoError(t, s.ReceiveBlock(ctx, b, root))
wg.Done()
}()
wg.Wait()
if recvd := len(s.stateNotifier.(*blockchainTesting.MockStateNotifier).ReceivedEvents()); recvd < 1 {
t.Errorf("Received %d state notifications, expected at least 1", recvd)
}
// Verify fork choice has processed the block. (Genesis block and the new block)
assert.Equal(t, 2, len(s.forkChoiceStore.Nodes()))
}
func TestService_ReceiveBlockInitialSync(t *testing.T) {
ctx := context.Background()
genesis, keys := testutil.DeterministicGenesisState(t, 64)
genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock {
blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot)
if err != nil {
t.Error(err)
}
return blk
}
type args struct {
block *ethpb.SignedBeaconBlock
}
tests := []struct {
name string
args args
wantErr bool
check func(*testing.T, *Service)
}{
{
name: "applies block with state transition",
args: args{
block: genFullBlock(t, testutil.DefaultBlockGenConfig(), 2 /*slot*/),
},
check: func(t *testing.T, s *Service) {
assert.Equal(t, uint64(2), s.head.state.Slot(), "Incorrect head state slot")
assert.Equal(t, uint64(2), s.head.block.Block.Slot, "Incorrect head block slot")
},
},
{
name: "notifies block processed on state feed",
args: args{
block: genFullBlock(t, testutil.DefaultBlockGenConfig(), 1 /*slot*/),
},
check: func(t *testing.T, s *Service) {
if recvd := len(s.stateNotifier.(*blockchainTesting.MockStateNotifier).ReceivedEvents()); recvd < 1 {
t.Errorf("Received %d state notifications, expected at least 1", recvd)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
db, stateSummaryCache := testDB.SetupDB(t)
genesisBlockRoot := bytesutil.ToBytes32(nil)
cfg := &Config{
BeaconDB: db,
ForkChoiceStore: protoarray.New(
0, // justifiedEpoch
0, // finalizedEpoch
genesisBlockRoot,
),
StateNotifier: &blockchainTesting.MockStateNotifier{RecordEvents: true},
StateGen: stategen.New(db, stateSummaryCache),
}
s, err := NewService(ctx, cfg)
require.NoError(t, err)
err = s.saveGenesisData(ctx, genesis)
require.NoError(t, err)
gBlk, err := s.beaconDB.GenesisBlock(ctx)
require.NoError(t, err)
gRoot, err := stateutil.BlockRoot(gBlk.Block)
s.finalizedCheckpt = &ethpb.Checkpoint{Root: gRoot[:]}
root, err := stateutil.BlockRoot(tt.args.block.Block)
require.NoError(t, err)
if err := s.ReceiveBlockInitialSync(ctx, tt.args.block, root); (err != nil) != tt.wantErr {
t.Errorf("ReceiveBlockInitialSync() error = %v, wantErr %v", err, tt.wantErr)
} else {
tt.check(t, s)
}
})
}
}
func TestService_ReceiveBlockBatch(t *testing.T) {
ctx := context.Background()
genesis, keys := testutil.DeterministicGenesisState(t, 64)
genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock {
blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot)
if err != nil {
t.Error(err)
}
return blk
}
type args struct {
block *ethpb.SignedBeaconBlock
}
tests := []struct {
name string
args args
wantErr bool
check func(*testing.T, *Service)
}{
{
name: "applies block with state transition",
args: args{
block: genFullBlock(t, testutil.DefaultBlockGenConfig(), 2 /*slot*/),
},
check: func(t *testing.T, s *Service) {
assert.Equal(t, uint64(2), s.head.state.Slot(), "Incorrect head state slot")
assert.Equal(t, uint64(2), s.head.block.Block.Slot, "Incorrect head block slot")
},
},
{
name: "notifies block processed on state feed",
args: args{
block: genFullBlock(t, testutil.DefaultBlockGenConfig(), 1 /*slot*/),
},
check: func(t *testing.T, s *Service) {
if recvd := len(s.stateNotifier.(*blockchainTesting.MockStateNotifier).ReceivedEvents()); recvd < 1 {
t.Errorf("Received %d state notifications, expected at least 1", recvd)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
db, stateSummaryCache := testDB.SetupDB(t)
genesisBlockRoot := bytesutil.ToBytes32(nil)
cfg := &Config{
BeaconDB: db,
ForkChoiceStore: protoarray.New(
0, // justifiedEpoch
0, // finalizedEpoch
genesisBlockRoot,
),
StateNotifier: &blockchainTesting.MockStateNotifier{RecordEvents: true},
StateGen: stategen.New(db, stateSummaryCache),
}
s, err := NewService(ctx, cfg)
require.NoError(t, err)
err = s.saveGenesisData(ctx, genesis)
require.NoError(t, err)
gBlk, err := s.beaconDB.GenesisBlock(ctx)
require.NoError(t, err)
gRoot, err := stateutil.BlockRoot(gBlk.Block)
s.finalizedCheckpt = &ethpb.Checkpoint{Root: gRoot[:]}
root, err := stateutil.BlockRoot(tt.args.block.Block)
require.NoError(t, err)
blks := []*ethpb.SignedBeaconBlock{tt.args.block}
roots := [][32]byte{root}
if err := s.ReceiveBlockBatch(ctx, blks, roots); (err != nil) != tt.wantErr {
t.Errorf("ReceiveBlockBatch() error = %v, wantErr %v", err, tt.wantErr)
} else {
tt.check(t, s)
}
})
}
}
func TestService_HasInitSyncBlock(t *testing.T) {
s, err := NewService(context.Background(), &Config{})
require.NoError(t, err)
r := [32]byte{'a'}
if s.HasInitSyncBlock(r) {
t.Error("Should not have block")
}
s.saveInitSyncBlock(r, testutil.NewBeaconBlock())
if !s.HasInitSyncBlock(r) {
t.Error("Should have block")
}
}

View File

@@ -1,6 +1,6 @@
// Package blockchain defines the life-cycle and status of the beacon chain
// as well as the Ethereum Serenity beacon chain fork-choice rule based on
// Casper Proof of Stake finality.
// Package blockchain defines the life-cycle of the blockchain at the core of
// eth2, including processing of new blocks and attestations using casper
// proof of stake.
package blockchain
import (
@@ -12,17 +12,14 @@ import (
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
"github.com/prysmaticlabs/prysm/beacon-chain/db/filters"
"github.com/prysmaticlabs/prysm/beacon-chain/flags"
f "github.com/prysmaticlabs/prysm/beacon-chain/forkchoice"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
@@ -33,50 +30,53 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/powchain"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/slotutil"
"go.opencensus.io/trace"
)
// Service represents a service that handles the internal
// logic of managing the full PoS beacon chain.
type Service struct {
ctx context.Context
cancel context.CancelFunc
beaconDB db.HeadAccessDatabase
depositCache *depositcache.DepositCache
chainStartFetcher powchain.ChainStartFetcher
attPool attestations.Pool
slashingPool *slashings.Pool
exitPool *voluntaryexits.Pool
genesisTime time.Time
p2p p2p.Broadcaster
maxRoutines int64
head *head
headLock sync.RWMutex
stateNotifier statefeed.Notifier
genesisRoot [32]byte
epochParticipation map[uint64]*precompute.Balance
epochParticipationLock sync.RWMutex
forkChoiceStore f.ForkChoicer
justifiedCheckpt *ethpb.Checkpoint
prevJustifiedCheckpt *ethpb.Checkpoint
bestJustifiedCheckpt *ethpb.Checkpoint
finalizedCheckpt *ethpb.Checkpoint
prevFinalizedCheckpt *ethpb.Checkpoint
nextEpochBoundarySlot uint64
voteLock sync.RWMutex
initSyncState map[[32]byte]*stateTrie.BeaconState
boundaryRoots [][32]byte
initSyncStateLock sync.RWMutex
checkpointState *cache.CheckpointStateCache
checkpointStateLock sync.Mutex
stateGen *stategen.State
opsService *attestations.Service
initSyncBlocks map[[32]byte]*ethpb.SignedBeaconBlock
initSyncBlocksLock sync.RWMutex
ctx context.Context
cancel context.CancelFunc
beaconDB db.HeadAccessDatabase
depositCache *depositcache.DepositCache
chainStartFetcher powchain.ChainStartFetcher
attPool attestations.Pool
slashingPool *slashings.Pool
exitPool *voluntaryexits.Pool
genesisTime time.Time
p2p p2p.Broadcaster
maxRoutines int
head *head
headLock sync.RWMutex
stateNotifier statefeed.Notifier
genesisRoot [32]byte
forkChoiceStore f.ForkChoicer
justifiedCheckpt *ethpb.Checkpoint
prevJustifiedCheckpt *ethpb.Checkpoint
bestJustifiedCheckpt *ethpb.Checkpoint
finalizedCheckpt *ethpb.Checkpoint
prevFinalizedCheckpt *ethpb.Checkpoint
nextEpochBoundarySlot uint64
voteLock sync.RWMutex
initSyncState map[[32]byte]*stateTrie.BeaconState
boundaryRoots [][32]byte
initSyncStateLock sync.RWMutex
checkpointState *cache.CheckpointStateCache
checkpointStateLock sync.Mutex
stateGen *stategen.State
opsService *attestations.Service
initSyncBlocks map[[32]byte]*ethpb.SignedBeaconBlock
initSyncBlocksLock sync.RWMutex
recentCanonicalBlocks map[[32]byte]bool
recentCanonicalBlocksLock sync.RWMutex
justifiedBalances []uint64
justifiedBalancesLock sync.RWMutex
}
// Config options for the service.
@@ -89,7 +89,7 @@ type Config struct {
ExitPool *voluntaryexits.Pool
SlashingPool *slashings.Pool
P2p p2p.Broadcaster
MaxRoutines int64
MaxRoutines int
StateNotifier statefeed.Notifier
ForkChoiceStore f.ForkChoicer
OpsService *attestations.Service
@@ -101,32 +101,32 @@ type Config struct {
func NewService(ctx context.Context, cfg *Config) (*Service, error) {
ctx, cancel := context.WithCancel(ctx)
return &Service{
ctx: ctx,
cancel: cancel,
beaconDB: cfg.BeaconDB,
depositCache: cfg.DepositCache,
chainStartFetcher: cfg.ChainStartFetcher,
attPool: cfg.AttPool,
exitPool: cfg.ExitPool,
slashingPool: cfg.SlashingPool,
p2p: cfg.P2p,
maxRoutines: cfg.MaxRoutines,
stateNotifier: cfg.StateNotifier,
epochParticipation: make(map[uint64]*precompute.Balance),
forkChoiceStore: cfg.ForkChoiceStore,
initSyncState: make(map[[32]byte]*stateTrie.BeaconState),
boundaryRoots: [][32]byte{},
checkpointState: cache.NewCheckpointStateCache(),
opsService: cfg.OpsService,
stateGen: cfg.StateGen,
initSyncBlocks: make(map[[32]byte]*ethpb.SignedBeaconBlock),
ctx: ctx,
cancel: cancel,
beaconDB: cfg.BeaconDB,
depositCache: cfg.DepositCache,
chainStartFetcher: cfg.ChainStartFetcher,
attPool: cfg.AttPool,
exitPool: cfg.ExitPool,
slashingPool: cfg.SlashingPool,
p2p: cfg.P2p,
maxRoutines: cfg.MaxRoutines,
stateNotifier: cfg.StateNotifier,
forkChoiceStore: cfg.ForkChoiceStore,
initSyncState: make(map[[32]byte]*stateTrie.BeaconState),
boundaryRoots: [][32]byte{},
checkpointState: cache.NewCheckpointStateCache(),
opsService: cfg.OpsService,
stateGen: cfg.StateGen,
initSyncBlocks: make(map[[32]byte]*ethpb.SignedBeaconBlock),
recentCanonicalBlocks: make(map[[32]byte]bool),
justifiedBalances: make([]uint64, 0),
}, nil
}
// Start a blockchain service's main event loop.
func (s *Service) Start() {
ctx := context.TODO()
beaconState, err := s.beaconDB.HeadState(ctx)
beaconState, err := s.beaconDB.HeadState(s.ctx)
if err != nil {
log.Fatalf("Could not fetch beacon state: %v", err)
}
@@ -134,22 +134,15 @@ func (s *Service) Start() {
// For running initial sync with state cache, in an event of restart, we use
// last finalized check point as start point to sync instead of head
// state. This is because we no longer save state every slot during sync.
cp, err := s.beaconDB.FinalizedCheckpoint(ctx)
cp, err := s.beaconDB.FinalizedCheckpoint(s.ctx)
if err != nil {
log.Fatalf("Could not fetch finalized cp: %v", err)
}
if beaconState == nil {
if !featureconfig.Get().DisableNewStateMgmt {
beaconState, err = s.stateGen.StateByRoot(ctx, bytesutil.ToBytes32(cp.Root))
if err != nil {
log.Fatalf("Could not fetch beacon state by root: %v", err)
}
} else {
beaconState, err = s.beaconDB.State(ctx, bytesutil.ToBytes32(cp.Root))
if err != nil {
log.Fatalf("Could not fetch beacon state: %v", err)
}
beaconState, err = s.stateGen.StateByRoot(s.ctx, bytesutil.ToBytes32(cp.Root))
if err != nil {
log.Fatalf("Could not fetch beacon state by root: %v", err)
}
}
@@ -161,34 +154,37 @@ func (s *Service) Start() {
log.Info("Blockchain data already exists in DB, initializing...")
s.genesisTime = time.Unix(int64(beaconState.GenesisTime()), 0)
s.opsService.SetGenesisTime(beaconState.GenesisTime())
if err := s.initializeChainInfo(ctx); err != nil {
if err := s.initializeChainInfo(s.ctx); err != nil {
log.Fatalf("Could not set up chain info: %v", err)
}
justifiedCheckpoint, err := s.beaconDB.JustifiedCheckpoint(ctx)
// We start a counter to genesis, if needed.
gState, err := s.beaconDB.GenesisState(s.ctx)
if err != nil {
log.Fatalf("Could not retrieve genesis state: %v", err)
}
go slotutil.CountdownToGenesis(s.ctx, s.genesisTime, uint64(gState.NumValidators()))
justifiedCheckpoint, err := s.beaconDB.JustifiedCheckpoint(s.ctx)
if err != nil {
log.Fatalf("Could not get justified checkpoint: %v", err)
}
finalizedCheckpoint, err := s.beaconDB.FinalizedCheckpoint(ctx)
finalizedCheckpoint, err := s.beaconDB.FinalizedCheckpoint(s.ctx)
if err != nil {
log.Fatalf("Could not get finalized checkpoint: %v", err)
}
// Resume fork choice.
s.justifiedCheckpt = stateTrie.CopyCheckpoint(justifiedCheckpoint)
if err := s.cacheJustifiedStateBalances(s.ctx, bytesutil.ToBytes32(s.justifiedCheckpt.Root)); err != nil {
log.Fatalf("Could not cache justified state balances: %v", err)
}
s.prevJustifiedCheckpt = stateTrie.CopyCheckpoint(justifiedCheckpoint)
s.bestJustifiedCheckpt = stateTrie.CopyCheckpoint(justifiedCheckpoint)
s.finalizedCheckpt = stateTrie.CopyCheckpoint(finalizedCheckpoint)
s.prevFinalizedCheckpt = stateTrie.CopyCheckpoint(finalizedCheckpoint)
s.resumeForkChoice(justifiedCheckpoint, finalizedCheckpoint)
if featureconfig.Get().DisableNewStateMgmt {
if finalizedCheckpoint.Epoch > 1 {
if err := s.pruneGarbageState(ctx, helpers.StartSlot(finalizedCheckpoint.Epoch)-params.BeaconConfig().SlotsPerEpoch); err != nil {
log.WithError(err).Warn("Could not prune old states")
}
}
}
s.stateNotifier.StateFeed().Send(&feed.Event{
Type: statefeed.Initialized,
Data: &statefeed.InitializedData{
@@ -217,7 +213,7 @@ func (s *Service) Start() {
return
}
log.WithField("starttime", data.StartTime).Debug("Received chain start event")
s.processChainStartTime(ctx, data.StartTime)
s.processChainStartTime(s.ctx, data.StartTime)
return
}
case <-s.ctx.Done():
@@ -242,6 +238,11 @@ func (s *Service) processChainStartTime(ctx context.Context, genesisTime time.Ti
if err != nil {
log.Fatalf("Could not initialize beacon chain: %v", err)
}
// We start a counter to genesis, if needed.
go slotutil.CountdownToGenesis(ctx, genesisTime, uint64(initializedState.NumValidators()))
// We send out a state initialized event to the rest of the services
// running in the beacon node.
s.stateNotifier.StateFeed().Send(&feed.Event{
Type: statefeed.Initialized,
Data: &statefeed.InitializedData{
@@ -294,13 +295,17 @@ func (s *Service) initializeBeaconChain(
// Stop the blockchain service's main event loop and associated goroutines.
func (s *Service) Stop() error {
defer s.cancel()
if s.stateGen != nil && s.head != nil && s.head.state != nil {
return s.stateGen.ForceCheckpoint(s.ctx, s.head.state.FinalizedCheckpoint().Root)
}
return nil
}
// Status always returns nil unless there is an error condition that causes
// this service to be unhealthy.
func (s *Service) Status() error {
if runtime.NumGoroutine() > int(s.maxRoutines) {
if runtime.NumGoroutine() > s.maxRoutines {
return fmt.Errorf("too many goroutines %d", runtime.NumGoroutine())
}
return nil
@@ -319,40 +324,41 @@ func (s *Service) saveGenesisData(ctx context.Context, genesisState *stateTrie.B
return err
}
genesisBlk := blocks.NewGenesisBlock(stateRoot[:])
genesisBlkRoot, err := ssz.HashTreeRoot(genesisBlk.Block)
genesisBlkRoot, err := stateutil.BlockRoot(genesisBlk.Block)
if err != nil {
return errors.Wrap(err, "could not get genesis block root")
}
s.genesisRoot = genesisBlkRoot
if err := s.beaconDB.SaveBlock(ctx, genesisBlk); err != nil {
return errors.Wrap(err, "could not save genesis block")
}
if !featureconfig.Get().DisableNewStateMgmt {
if err := s.stateGen.SaveState(ctx, genesisBlkRoot, genesisState); err != nil {
return errors.Wrap(err, "could not save genesis state")
}
if err := s.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Slot: 0,
Root: genesisBlkRoot[:],
}); err != nil {
return err
}
} else {
if err := s.beaconDB.SaveState(ctx, genesisState, genesisBlkRoot); err != nil {
return errors.Wrap(err, "could not save genesis state")
}
if err := s.beaconDB.SaveState(ctx, genesisState, genesisBlkRoot); err != nil {
return errors.Wrap(err, "could not save genesis state")
}
if err := s.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Slot: 0,
Root: genesisBlkRoot[:],
}); err != nil {
return err
}
s.stateGen.SaveFinalizedState(0, genesisBlkRoot, genesisState)
if err := s.beaconDB.SaveHeadBlockRoot(ctx, genesisBlkRoot); err != nil {
return errors.Wrap(err, "could not save head block root")
}
if err := s.beaconDB.SaveGenesisBlockRoot(ctx, genesisBlkRoot); err != nil {
return errors.Wrap(err, "could save genesis block root")
return errors.Wrap(err, "could not save genesis block root")
}
genesisCheckpoint := &ethpb.Checkpoint{Root: genesisBlkRoot[:]}
// Finalized checkpoint at genesis is a zero hash.
genesisCheckpoint := genesisState.FinalizedCheckpoint()
// Add the genesis block to the fork choice store.
s.justifiedCheckpt = stateTrie.CopyCheckpoint(genesisCheckpoint)
if err := s.cacheJustifiedStateBalances(ctx, genesisBlkRoot); err != nil {
return err
}
s.prevJustifiedCheckpt = stateTrie.CopyCheckpoint(genesisCheckpoint)
s.bestJustifiedCheckpt = stateTrie.CopyCheckpoint(genesisCheckpoint)
s.finalizedCheckpt = stateTrie.CopyCheckpoint(genesisCheckpoint)
@@ -362,6 +368,7 @@ func (s *Service) saveGenesisData(ctx context.Context, genesisState *stateTrie.B
genesisBlk.Block.Slot,
genesisBlkRoot,
params.BeaconConfig().ZeroHash,
[32]byte{},
genesisCheckpoint.Epoch,
genesisCheckpoint.Epoch); err != nil {
log.Fatalf("Could not process genesis block for fork choice: %v", err)
@@ -381,7 +388,7 @@ func (s *Service) initializeChainInfo(ctx context.Context) error {
if genesisBlock == nil {
return errors.New("no genesis block in db")
}
genesisBlkRoot, err := ssz.HashTreeRoot(genesisBlock.Block)
genesisBlkRoot, err := stateutil.BlockRoot(genesisBlock.Block)
if err != nil {
return errors.Wrap(err, "could not get signing root of genesis block")
}
@@ -392,7 +399,7 @@ func (s *Service) initializeChainInfo(ctx context.Context) error {
if err != nil {
return errors.Wrap(err, "could not retrieve head block")
}
headRoot, err := ssz.HashTreeRoot(headBlock.Block)
headRoot, err := stateutil.BlockRoot(headBlock.Block)
if err != nil {
return errors.Wrap(err, "could not hash head block")
}
@@ -415,20 +422,14 @@ func (s *Service) initializeChainInfo(ctx context.Context) error {
}
finalizedRoot := bytesutil.ToBytes32(finalized.Root)
var finalizedState *stateTrie.BeaconState
if !featureconfig.Get().DisableNewStateMgmt {
finalizedRoot = s.beaconDB.LastArchivedIndexRoot(ctx)
finalizedState, err = s.stateGen.Resume(ctx)
if err != nil {
return errors.Wrap(err, "could not get finalized state from db")
}
if finalizedRoot == params.BeaconConfig().ZeroHash {
finalizedRoot = bytesutil.ToBytes32(finalized.Root)
}
} else {
finalizedState, err = s.beaconDB.State(ctx, bytesutil.ToBytes32(finalized.Root))
if err != nil {
return errors.Wrap(err, "could not get finalized state from db")
}
finalizedState, err = s.stateGen.Resume(ctx)
if err != nil {
return errors.Wrap(err, "could not get finalized state from db")
}
finalizedRoot = s.beaconDB.LastArchivedRoot(ctx)
if finalizedRoot == params.BeaconConfig().ZeroHash {
finalizedRoot = bytesutil.ToBytes32(finalized.Root)
}
finalizedBlock, err := s.beaconDB.Block(ctx, finalizedRoot)
@@ -444,29 +445,6 @@ func (s *Service) initializeChainInfo(ctx context.Context) error {
return nil
}
// This is called when a client starts from a non-genesis slot. It deletes the states in DB
// from slot 1 (avoid genesis state) to `slot`.
func (s *Service) pruneGarbageState(ctx context.Context, slot uint64) error {
if featureconfig.Get().DontPruneStateStartUp {
return nil
}
filter := filters.NewFilter().SetStartSlot(1).SetEndSlot(slot)
roots, err := s.beaconDB.BlockRoots(ctx, filter)
if err != nil {
return err
}
if err := s.beaconDB.DeleteStates(ctx, roots); err != nil {
return err
}
if err := s.beaconDB.SaveLastArchivedIndex(ctx, 0); err != nil {
return err
}
return nil
}
// This is called when a client starts from non-genesis slot. This passes last justified and finalized
// information to fork choice service to initializes fork choice store.
func (s *Service) resumeForkChoice(justifiedCheckpoint *ethpb.Checkpoint, finalizedCheckpoint *ethpb.Checkpoint) {

View File

@@ -6,6 +6,7 @@ import (
"testing"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/sirupsen/logrus"
)
@@ -15,17 +16,12 @@ func init() {
}
func TestChainService_SaveHead_DataRace(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
s := &Service{
beaconDB: db,
}
go func() {
if err := s.saveHead(context.Background(), [32]byte{}, ); err != nil {
t.Fatal(err)
}
require.NoError(t, s.saveHead(context.Background(), [32]byte{}))
}()
if err := s.saveHead(context.Background(), [32]byte{}, ); err != nil {
t.Fatal(err)
}
require.NoError(t, s.saveHead(context.Background(), [32]byte{}))
}

View File

@@ -11,16 +11,13 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
ssz "github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache"
b "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
"github.com/prysmaticlabs/prysm/beacon-chain/db/filters"
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
"github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations"
@@ -28,11 +25,15 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/powchain"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
protodb "github.com/prysmaticlabs/prysm/proto/beacon/db"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/event"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/sirupsen/logrus"
logTest "github.com/sirupsen/logrus/hooks/test"
)
@@ -42,42 +43,6 @@ func init() {
logrus.SetOutput(ioutil.Discard)
}
type store struct {
headRoot []byte
}
func (s *store) OnBlock(ctx context.Context, b *ethpb.SignedBeaconBlock) (*beaconstate.BeaconState, error) {
return nil, nil
}
func (s *store) OnBlockCacheFilteredTree(ctx context.Context, b *ethpb.SignedBeaconBlock) (*beaconstate.BeaconState, error) {
return nil, nil
}
func (s *store) OnBlockInitialSyncStateTransition(ctx context.Context, b *ethpb.SignedBeaconBlock) (*beaconstate.BeaconState, error) {
return nil, nil
}
func (s *store) OnAttestation(ctx context.Context, a *ethpb.Attestation) ([]uint64, error) {
return nil, nil
}
func (s *store) GenesisStore(ctx context.Context, justifiedCheckpoint *ethpb.Checkpoint, finalizedCheckpoint *ethpb.Checkpoint) error {
return nil
}
func (s *store) FinalizedCheckpt() *ethpb.Checkpoint {
return nil
}
func (s *store) JustifiedCheckpt() *ethpb.Checkpoint {
return nil
}
func (s *store) Head(ctx context.Context) ([]byte, error) {
return s.headRoot, nil
}
type mockBeaconNode struct {
stateFeed *event.Feed
}
@@ -99,10 +64,15 @@ func (mb *mockBroadcaster) Broadcast(_ context.Context, _ proto.Message) error {
return nil
}
func (mb *mockBroadcaster) BroadcastAttestation(_ context.Context, _ uint64, _ *ethpb.Attestation) error {
mb.broadcastCalled = true
return nil
}
var _ = p2p.Broadcaster(&mockBroadcaster{})
func setupBeaconChain(t *testing.T, beaconDB db.Database) *Service {
endpoint := "ws://127.0.0.1"
func setupBeaconChain(t *testing.T, beaconDB db.Database, sc *cache.StateSummaryCache) *Service {
endpoint := "http://127.0.0.1"
ctx := context.Background()
var web3Service *powchain.Service
var err error
@@ -122,193 +92,104 @@ func setupBeaconChain(t *testing.T, beaconDB db.Database) *Service {
},
DepositContainers: []*protodb.DepositContainer{},
})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
web3Service, err = powchain.NewService(ctx, &powchain.Web3ServiceConfig{
BeaconDB: beaconDB,
ETH1Endpoint: endpoint,
HTTPEndPoint: endpoint,
DepositContract: common.Address{},
})
if err != nil {
t.Fatalf("unable to set up web3 service: %v", err)
}
require.NoError(t, err, "Unable to set up web3 service")
opsService, err := attestations.NewService(ctx, &attestations.Config{Pool: attestations.NewPool()})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
depositCache, err := depositcache.NewDepositCache()
require.NoError(t, err)
cfg := &Config{
BeaconBlockBuf: 0,
BeaconDB: beaconDB,
DepositCache: depositcache.NewDepositCache(),
DepositCache: depositCache,
ChainStartFetcher: web3Service,
P2p: &mockBroadcaster{},
StateNotifier: &mockBeaconNode{},
AttPool: attestations.NewPool(),
StateGen: stategen.New(beaconDB, cache.NewStateSummaryCache()),
StateGen: stategen.New(beaconDB, sc),
ForkChoiceStore: protoarray.New(0, 0, params.BeaconConfig().ZeroHash),
OpsService: opsService,
}
chainService, err := NewService(ctx, cfg)
if err != nil {
t.Fatalf("unable to setup chain service: %v", err)
// Safe a state in stategen to purposes of testing a service stop / shutdown.
if err := cfg.StateGen.SaveState(ctx, bytesutil.ToBytes32(bState.FinalizedCheckpoint().Root), bState); err != nil {
t.Fatal(err)
}
chainService, err := NewService(ctx, cfg)
require.NoError(t, err, "Unable to setup chain service")
chainService.genesisTime = time.Unix(1, 0) // non-zero time
return chainService
}
func TestChainStartStop_Uninitialized(t *testing.T) {
hook := logTest.NewGlobal()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
chainService := setupBeaconChain(t, db)
// Listen for state events.
stateSubChannel := make(chan *feed.Event, 1)
stateSub := chainService.stateNotifier.StateFeed().Subscribe(stateSubChannel)
// Test the chain start state notifier.
genesisTime := time.Unix(1, 0)
chainService.Start()
event := &feed.Event{
Type: statefeed.ChainStarted,
Data: &statefeed.ChainStartedData{
StartTime: genesisTime,
},
}
// Send in a loop to ensure it is delivered (busy wait for the service to subscribe to the state feed).
for sent := 1; sent == 1; {
sent = chainService.stateNotifier.StateFeed().Send(event)
if sent == 1 {
// Flush our local subscriber.
<-stateSubChannel
}
}
// Now wait for notification the state is ready.
for stateInitialized := false; stateInitialized == false; {
recv := <-stateSubChannel
if recv.Type == statefeed.Initialized {
stateInitialized = true
}
}
stateSub.Unsubscribe()
beaconState, err := db.HeadState(context.Background())
if err != nil {
t.Fatal(err)
}
if beaconState == nil || beaconState.Slot() != 0 {
t.Error("Expected canonical state feed to send a state with genesis block")
}
if err := chainService.Stop(); err != nil {
t.Fatalf("Unable to stop chain service: %v", err)
}
// The context should have been canceled.
if chainService.ctx.Err() != context.Canceled {
t.Error("Context was not canceled")
}
testutil.AssertLogsContain(t, hook, "Waiting")
testutil.AssertLogsContain(t, hook, "Initialized beacon chain genesis state")
}
func TestChainStartStop_Initialized(t *testing.T) {
hook := logTest.NewGlobal()
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
chainService := setupBeaconChain(t, db)
chainService := setupBeaconChain(t, db, sc)
genesisBlk := b.NewGenesisBlock([]byte{})
blkRoot, err := ssz.HashTreeRoot(genesisBlk.Block)
if err != nil {
t.Fatal(err)
}
if err := db.SaveBlock(ctx, genesisBlk); err != nil {
t.Fatal(err)
}
genesisBlk := testutil.NewBeaconBlock()
blkRoot, err := stateutil.BlockRoot(genesisBlk.Block)
require.NoError(t, err)
require.NoError(t, db.SaveBlock(ctx, genesisBlk))
s := testutil.NewBeaconState()
if err := s.SetSlot(1); err != nil {
t.Fatal(err)
}
if err := db.SaveState(ctx, s, blkRoot); err != nil {
t.Fatal(err)
}
if err := db.SaveHeadBlockRoot(ctx, blkRoot); err != nil {
t.Fatal(err)
}
if err := db.SaveGenesisBlockRoot(ctx, blkRoot); err != nil {
t.Fatal(err)
}
if err := db.SaveJustifiedCheckpoint(ctx, &ethpb.Checkpoint{Root: blkRoot[:]}); err != nil {
t.Fatal(err)
}
require.NoError(t, s.SetSlot(1))
require.NoError(t, db.SaveState(ctx, s, blkRoot))
require.NoError(t, db.SaveHeadBlockRoot(ctx, blkRoot))
require.NoError(t, db.SaveGenesisBlockRoot(ctx, blkRoot))
require.NoError(t, db.SaveJustifiedCheckpoint(ctx, &ethpb.Checkpoint{Root: blkRoot[:]}))
// Test the start function.
chainService.Start()
if err := chainService.Stop(); err != nil {
t.Fatalf("unable to stop chain service: %v", err)
}
require.NoError(t, chainService.Stop(), "Unable to stop chain service")
// The context should have been canceled.
if chainService.ctx.Err() != context.Canceled {
t.Error("context was not canceled")
}
assert.Equal(t, context.Canceled, chainService.ctx.Err(), "Context was not canceled")
testutil.AssertLogsContain(t, hook, "data already exists")
}
func TestChainService_InitializeBeaconChain(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
helpers.ClearCache()
db, sc := testDB.SetupDB(t)
ctx := context.Background()
bc := setupBeaconChain(t, db)
bc := setupBeaconChain(t, db, sc)
var err error
// Set up 10 deposits pre chain start for validators to register
count := uint64(10)
deposits, _, err := testutil.DeterministicDepositsAndKeys(count)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
trie, _, err := testutil.DepositTrieFromDeposits(deposits)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
hashTreeRoot := trie.HashTreeRoot()
genState, err := state.EmptyGenesisState()
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
err = genState.SetEth1Data(&ethpb.Eth1Data{
DepositRoot: hashTreeRoot[:],
DepositCount: uint64(len(deposits)),
})
for _, deposit := range deposits {
genState, err = b.ProcessPreGenesisDeposit(ctx, genState, deposit)
if err != nil {
t.Fatal(err)
}
}
genState, err = b.ProcessPreGenesisDeposits(ctx, genState, deposits)
require.NoError(t, err)
if _, err := bc.initializeBeaconChain(ctx, time.Unix(0, 0), genState, &ethpb.Eth1Data{
DepositRoot: hashTreeRoot[:],
}); err != nil {
t.Fatal(err)
}
_, err = bc.initializeBeaconChain(ctx, time.Unix(0, 0), genState, &ethpb.Eth1Data{DepositRoot: hashTreeRoot[:]})
require.NoError(t, err)
if _, err := bc.HeadState(ctx); err != nil {
t.Error(err)
}
_, err = bc.HeadState(ctx)
assert.NoError(t, err)
headBlk, err := bc.HeadBlock(ctx)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if headBlk == nil {
t.Error("Head state can't be nil after initialize beacon chain")
}
@@ -318,248 +199,126 @@ func TestChainService_InitializeBeaconChain(t *testing.T) {
}
func TestChainService_InitializeChainInfo(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
ctx := context.Background()
genesis := b.NewGenesisBlock([]byte{})
genesisRoot, err := ssz.HashTreeRoot(genesis.Block)
if err != nil {
t.Fatal(err)
}
if err := db.SaveGenesisBlockRoot(ctx, genesisRoot); err != nil {
t.Fatal(err)
}
if err := db.SaveBlock(ctx, genesis); err != nil {
t.Fatal(err)
}
genesis := testutil.NewBeaconBlock()
genesisRoot, err := stateutil.BlockRoot(genesis.Block)
require.NoError(t, err)
require.NoError(t, db.SaveGenesisBlockRoot(ctx, genesisRoot))
require.NoError(t, db.SaveBlock(ctx, genesis))
finalizedSlot := params.BeaconConfig().SlotsPerEpoch*2 + 1
headBlock := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: finalizedSlot, ParentRoot: genesisRoot[:]}}
headBlock := testutil.NewBeaconBlock()
headBlock.Block.Slot = finalizedSlot
headBlock.Block.ParentRoot = bytesutil.PadTo(genesisRoot[:], 32)
headState := testutil.NewBeaconState()
if err := headState.SetSlot(finalizedSlot); err != nil {
t.Fatal(err)
}
if err := headState.SetGenesisValidatorRoot(params.BeaconConfig().ZeroHash[:]); err != nil {
t.Fatal(err)
}
headRoot, err := ssz.HashTreeRoot(headBlock.Block)
if err != nil {
t.Fatal(err)
}
if err := db.SaveState(ctx, headState, headRoot); err != nil {
t.Fatal(err)
}
if err := db.SaveState(ctx, headState, genesisRoot); err != nil {
t.Fatal(err)
}
if err := db.SaveBlock(ctx, headBlock); err != nil {
t.Fatal(err)
}
require.NoError(t, headState.SetSlot(finalizedSlot))
require.NoError(t, headState.SetGenesisValidatorRoot(params.BeaconConfig().ZeroHash[:]))
headRoot, err := stateutil.BlockRoot(headBlock.Block)
require.NoError(t, err)
require.NoError(t, db.SaveState(ctx, headState, headRoot))
require.NoError(t, db.SaveState(ctx, headState, genesisRoot))
require.NoError(t, db.SaveBlock(ctx, headBlock))
if err := db.SaveFinalizedCheckpoint(ctx, &ethpb.Checkpoint{
Epoch: helpers.SlotToEpoch(finalizedSlot),
Root: headRoot[:],
}); err != nil {
t.Fatal(err)
}
if err := db.SaveBlock(ctx, headBlock); err != nil {
t.Fatal(err)
}
c := &Service{beaconDB: db, stateGen: stategen.New(db, cache.NewStateSummaryCache())}
if err := c.initializeChainInfo(ctx); err != nil {
t.Fatal(err)
}
c := &Service{beaconDB: db, stateGen: stategen.New(db, sc)}
require.NoError(t, c.initializeChainInfo(ctx))
headBlk, err := c.HeadBlock(ctx)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(headBlk, headBlock) {
t.Error("head block incorrect")
}
require.NoError(t, err)
assert.DeepEqual(t, headBlock, headBlk, "Head block incorrect")
s, err := c.HeadState(ctx)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(s.InnerStateUnsafe(), headState.InnerStateUnsafe()) {
t.Error("head state incorrect")
}
if headBlock.Block.Slot != c.HeadSlot() {
t.Error("head slot incorrect")
}
require.NoError(t, err)
assert.DeepEqual(t, headState.InnerStateUnsafe(), s.InnerStateUnsafe(), "Head state incorrect")
assert.Equal(t, c.HeadSlot(), headBlock.Block.Slot, "Head slot incorrect")
r, err := c.HeadRoot(context.Background())
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if !bytes.Equal(headRoot[:], r) {
t.Error("head slot incorrect")
}
if c.genesisRoot != genesisRoot {
t.Error("genesis block root incorrect")
}
assert.Equal(t, genesisRoot, c.genesisRoot, "Genesis block root incorrect")
}
func TestChainService_SaveHeadNoDB(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, sc := testDB.SetupDB(t)
ctx := context.Background()
s := &Service{
beaconDB: db,
stateGen: stategen.New(db, cache.NewStateSummaryCache()),
stateGen: stategen.New(db, sc),
}
b := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Slot: 1}}
r, err := ssz.HashTreeRoot(b)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
newState := testutil.NewBeaconState()
if err := s.stateGen.SaveState(ctx, r, newState); err != nil {
t.Fatal(err)
}
if err := s.saveHeadNoDB(ctx, b, r); err != nil {
t.Fatal(err)
}
require.NoError(t, s.stateGen.SaveState(ctx, r, newState))
require.NoError(t, s.saveHeadNoDB(ctx, b, r, newState))
newB, err := s.beaconDB.HeadBlock(ctx)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if reflect.DeepEqual(newB, b) {
t.Error("head block should not be equal")
}
}
func TestChainService_PruneOldStates(t *testing.T) {
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
ctx := context.Background()
s := &Service{
beaconDB: db,
}
for i := 0; i < 100; i++ {
block := &ethpb.BeaconBlock{Slot: uint64(i)}
if err := s.beaconDB.SaveBlock(ctx, &ethpb.SignedBeaconBlock{Block: block}); err != nil {
t.Fatal(err)
}
r, err := ssz.HashTreeRoot(block)
if err != nil {
t.Fatal(err)
}
newState := testutil.NewBeaconState()
if err := newState.SetSlot(uint64(i)); err != nil {
t.Fatal(err)
}
if err := s.beaconDB.SaveState(ctx, newState, r); err != nil {
t.Fatal(err)
}
}
// Delete half of the states.
if err := s.pruneGarbageState(ctx, 50); err != nil {
t.Fatal(err)
}
filter := filters.NewFilter().SetStartSlot(1).SetEndSlot(100)
roots, err := s.beaconDB.BlockRoots(ctx, filter)
if err != nil {
t.Fatal(err)
}
for i := 1; i < 50; i++ {
s, err := s.beaconDB.State(ctx, roots[i])
if err != nil {
t.Fatal(err)
}
if s != nil {
t.Errorf("wanted nil for slot %d", i)
}
}
}
func TestHasBlock_ForkChoiceAndDB(t *testing.T) {
ctx := context.Background()
db := testDB.SetupDB(t)
defer testDB.TeardownDB(t, db)
db, _ := testDB.SetupDB(t)
s := &Service{
forkChoiceStore: protoarray.New(0, 0, [32]byte{}),
finalizedCheckpt: &ethpb.Checkpoint{},
beaconDB: db,
}
block := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Body: &ethpb.BeaconBlockBody{}}}
r, err := ssz.HashTreeRoot(block.Block)
if err != nil {
t.Fatal(err)
}
r, err := stateutil.BlockRoot(block.Block)
require.NoError(t, err)
bs := &pb.BeaconState{FinalizedCheckpoint: &ethpb.Checkpoint{}, CurrentJustifiedCheckpoint: &ethpb.Checkpoint{}}
state, err := beaconstate.InitializeFromProto(bs)
if err != nil {
t.Fatal(err)
}
if err := s.insertBlockToForkChoiceStore(ctx, block.Block, r, state); err != nil {
t.Fatal(err)
}
require.NoError(t, err)
require.NoError(t, s.insertBlockAndAttestationsToForkChoiceStore(ctx, block.Block, r, state))
if s.hasBlock(ctx, [32]byte{}) {
t.Error("Should not have block")
}
if !s.hasBlock(ctx, r) {
t.Error("Should have block")
}
assert.Equal(t, false, s.hasBlock(ctx, [32]byte{}), "Should not have block")
assert.Equal(t, true, s.hasBlock(ctx, r), "Should have block")
}
func BenchmarkHasBlockDB(b *testing.B) {
db := testDB.SetupDB(b)
defer testDB.TeardownDB(b, db)
db, _ := testDB.SetupDB(b)
ctx := context.Background()
s := &Service{
beaconDB: db,
}
block := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{}}
if err := s.beaconDB.SaveBlock(ctx, block); err != nil {
b.Fatal(err)
}
r, err := ssz.HashTreeRoot(block.Block)
if err != nil {
b.Fatal(err)
}
require.NoError(b, s.beaconDB.SaveBlock(ctx, block))
r, err := stateutil.BlockRoot(block.Block)
require.NoError(b, err)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if !s.beaconDB.HasBlock(ctx, r) {
b.Fatal("Block is not in DB")
}
require.Equal(b, true, s.beaconDB.HasBlock(ctx, r), "Block is not in DB")
}
}
func BenchmarkHasBlockForkChoiceStore(b *testing.B) {
ctx := context.Background()
db := testDB.SetupDB(b)
defer testDB.TeardownDB(b, db)
db, _ := testDB.SetupDB(b)
s := &Service{
forkChoiceStore: protoarray.New(0, 0, [32]byte{}),
finalizedCheckpt: &ethpb.Checkpoint{},
beaconDB: db,
}
block := &ethpb.SignedBeaconBlock{Block: &ethpb.BeaconBlock{Body: &ethpb.BeaconBlockBody{}}}
r, err := ssz.HashTreeRoot(block.Block)
if err != nil {
b.Fatal(err)
}
r, err := stateutil.BlockRoot(block.Block)
require.NoError(b, err)
bs := &pb.BeaconState{FinalizedCheckpoint: &ethpb.Checkpoint{}, CurrentJustifiedCheckpoint: &ethpb.Checkpoint{}}
state, err := beaconstate.InitializeFromProto(bs)
if err != nil {
b.Fatal(err)
}
if err := s.insertBlockToForkChoiceStore(ctx, block.Block, r, state); err != nil {
b.Fatal(err)
}
require.NoError(b, err)
require.NoError(b, s.insertBlockAndAttestationsToForkChoiceStore(ctx, block.Block, r, state))
b.ResetTimer()
for i := 0; i < b.N; i++ {
if !s.forkChoiceStore.HasNode(r) {
b.Fatal("Block is not in fork choice store")
}
require.Equal(b, true, s.forkChoiceStore.HasNode(r), "Block is not in fork choice store")
}
}

View File

@@ -1,25 +1,30 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
load("@prysm//tools/go:def.bzl", "go_library")
go_library(
name = "go_default_library",
testonly = True,
srcs = ["mock.go"],
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing",
visibility = ["//beacon-chain:__subpackages__"],
visibility = [
"//beacon-chain:__subpackages__",
"//fuzz:__pkg__",
],
deps = [
"//beacon-chain/core/epoch/precompute:go_default_library",
"//beacon-chain/core/feed:go_default_library",
"//beacon-chain/core/feed/block:go_default_library",
"//beacon-chain/core/feed/operation:go_default_library",
"//beacon-chain/core/feed/state:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/forkchoice/protoarray:go_default_library",
"//beacon-chain/state:go_default_library",
"//beacon-chain/state/stateutil:go_default_library",
"//proto/beacon/p2p/v1:go_default_library",
"//shared/event:go_default_library",
"//shared/params:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_prysmaticlabs_go_ssz//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
],
)

View File

@@ -1,20 +1,25 @@
// Package testing includes useful mocks for writing unit
// tests which depend on logic from the blockchain package.
package testing
import (
"bytes"
"context"
"sync"
"time"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
blockfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/block"
opfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/operation"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
"github.com/prysmaticlabs/prysm/beacon-chain/forkchoice/protoarray"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/event"
"github.com/prysmaticlabs/prysm/shared/params"
@@ -34,11 +39,14 @@ type ChainService struct {
Genesis time.Time
ValidatorsRoot [32]byte
Fork *pb.Fork
ETH1Data *ethpb.Eth1Data
DB db.Database
stateNotifier statefeed.Notifier
blockNotifier blockfeed.Notifier
opNotifier opfeed.Notifier
ValidAttestation bool
ForkChoiceStore *protoarray.Store
VerifyBlkDescendantErr error
}
// StateNotifier mocks the same method in the chain service.
@@ -73,12 +81,40 @@ func (msn *MockBlockNotifier) BlockFeed() *event.Feed {
// MockStateNotifier mocks the state notifier.
type MockStateNotifier struct {
feed *event.Feed
recv []*feed.Event
recvLock sync.Mutex
recvCh chan *feed.Event
RecordEvents bool
}
// ReceivedEvents returns the events received by the state feed in this mock.
func (msn *MockStateNotifier) ReceivedEvents() []*feed.Event {
msn.recvLock.Lock()
defer msn.recvLock.Unlock()
return msn.recv
}
// StateFeed returns a state feed.
func (msn *MockStateNotifier) StateFeed() *event.Feed {
if msn.feed == nil {
if msn.feed == nil && msn.recvCh == nil {
msn.feed = new(event.Feed)
if msn.RecordEvents {
msn.recvCh = make(chan *feed.Event)
sub := msn.feed.Subscribe(msn.recvCh)
go func() {
select {
case evt := <-msn.recvCh:
msn.recvLock.Lock()
msn.recv = append(msn.recv, evt)
msn.recvLock.Unlock()
case <-sub.Err():
sub.Unsubscribe()
}
}()
}
}
return msn.feed
}
@@ -104,23 +140,8 @@ func (mon *MockOperationNotifier) OperationFeed() *event.Feed {
return mon.feed
}
// ReceiveBlock mocks ReceiveBlock method in chain service.
func (ms *ChainService) ReceiveBlock(ctx context.Context, block *ethpb.SignedBeaconBlock) error {
return nil
}
// ReceiveBlockNoVerify mocks ReceiveBlockNoVerify method in chain service.
func (ms *ChainService) ReceiveBlockNoVerify(ctx context.Context, block *ethpb.SignedBeaconBlock) error {
return nil
}
// ReceiveBlockNoPubsub mocks ReceiveBlockNoPubsub method in chain service.
func (ms *ChainService) ReceiveBlockNoPubsub(ctx context.Context, block *ethpb.SignedBeaconBlock) error {
return nil
}
// ReceiveBlockNoPubsubForkchoice mocks ReceiveBlockNoPubsubForkchoice method in chain service.
func (ms *ChainService) ReceiveBlockNoPubsubForkchoice(ctx context.Context, block *ethpb.SignedBeaconBlock) error {
// ReceiveBlockInitialSync mocks ReceiveBlockInitialSync method in chain service.
func (ms *ChainService) ReceiveBlockInitialSync(ctx context.Context, block *ethpb.SignedBeaconBlock, blockRoot [32]byte) error {
if ms.State == nil {
ms.State = &stateTrie.BeaconState{}
}
@@ -131,7 +152,63 @@ func (ms *ChainService) ReceiveBlockNoPubsubForkchoice(ctx context.Context, bloc
return err
}
ms.BlocksReceived = append(ms.BlocksReceived, block)
signingRoot, err := ssz.HashTreeRoot(block.Block)
signingRoot, err := stateutil.BlockRoot(block.Block)
if err != nil {
return err
}
if ms.DB != nil {
if err := ms.DB.SaveBlock(ctx, block); err != nil {
return err
}
logrus.Infof("Saved block with root: %#x at slot %d", signingRoot, block.Block.Slot)
}
ms.Root = signingRoot[:]
ms.Block = block
return nil
}
// ReceiveBlockBatch processes blocks in batches from initial-sync.
func (ms *ChainService) ReceiveBlockBatch(ctx context.Context, blks []*ethpb.SignedBeaconBlock, roots [][32]byte) error {
if ms.State == nil {
ms.State = &stateTrie.BeaconState{}
}
for _, block := range blks {
if !bytes.Equal(ms.Root, block.Block.ParentRoot) {
return errors.Errorf("wanted %#x but got %#x", ms.Root, block.Block.ParentRoot)
}
if err := ms.State.SetSlot(block.Block.Slot); err != nil {
return err
}
ms.BlocksReceived = append(ms.BlocksReceived, block)
signingRoot, err := stateutil.BlockRoot(block.Block)
if err != nil {
return err
}
if ms.DB != nil {
if err := ms.DB.SaveBlock(ctx, block); err != nil {
return err
}
logrus.Infof("Saved block with root: %#x at slot %d", signingRoot, block.Block.Slot)
}
ms.Root = signingRoot[:]
ms.Block = block
}
return nil
}
// ReceiveBlock mocks ReceiveBlock method in chain service.
func (ms *ChainService) ReceiveBlock(ctx context.Context, block *ethpb.SignedBeaconBlock, blockRoot [32]byte) error {
if ms.State == nil {
ms.State = &stateTrie.BeaconState{}
}
if !bytes.Equal(ms.Root, block.Block.ParentRoot) {
return errors.Errorf("wanted %#x but got %#x", ms.Root, block.Block.ParentRoot)
}
if err := ms.State.SetSlot(block.Block.Slot); err != nil {
return err
}
ms.BlocksReceived = append(ms.BlocksReceived, block)
signingRoot, err := stateutil.BlockRoot(block.Block)
if err != nil {
return err
}
@@ -200,8 +277,13 @@ func (ms *ChainService) ReceiveAttestationNoPubsub(context.Context, *ethpb.Attes
return nil
}
// AttestationPreState mocks AttestationPreState method in chain service.
func (ms *ChainService) AttestationPreState(ctx context.Context, att *ethpb.Attestation) (*stateTrie.BeaconState, error) {
return ms.State, nil
}
// HeadValidatorsIndices mocks the same method in the chain service.
func (ms *ChainService) HeadValidatorsIndices(epoch uint64) ([]uint64, error) {
func (ms *ChainService) HeadValidatorsIndices(ctx context.Context, epoch uint64) ([]uint64, error) {
if ms.State == nil {
return []uint64{}, nil
}
@@ -209,10 +291,20 @@ func (ms *ChainService) HeadValidatorsIndices(epoch uint64) ([]uint64, error) {
}
// HeadSeed mocks the same method in the chain service.
func (ms *ChainService) HeadSeed(epoch uint64) ([32]byte, error) {
func (ms *ChainService) HeadSeed(ctx context.Context, epoch uint64) ([32]byte, error) {
return helpers.Seed(ms.State, epoch, params.BeaconConfig().DomainBeaconAttester)
}
// HeadETH1Data provides the current ETH1Data of the head state.
func (ms *ChainService) HeadETH1Data() *ethpb.Eth1Data {
return ms.ETH1Data
}
// ProtoArrayStore mocks the same method in the chain service.
func (ms *ChainService) ProtoArrayStore() *protoarray.Store {
return ms.ForkChoiceStore
}
// GenesisTime mocks the same method in the chain service.
func (ms *ChainService) GenesisTime() time.Time {
return ms.Genesis
@@ -238,6 +330,12 @@ func (ms *ChainService) IsValidAttestation(ctx context.Context, att *ethpb.Attes
return ms.ValidAttestation
}
// IsCanonical returns and determines whether a block with the provided root is part of
// the canonical chain.
func (ms *ChainService) IsCanonical(ctx context.Context, blockRoot [32]byte) (bool, error) {
return true, nil
}
// ClearCachedStates does nothing.
func (ms *ChainService) ClearCachedStates() {}
@@ -245,3 +343,13 @@ func (ms *ChainService) ClearCachedStates() {}
func (ms *ChainService) HasInitSyncBlock(root [32]byte) bool {
return false
}
// HeadGenesisValidatorRoot mocks HeadGenesisValidatorRoot method in chain service.
func (ms *ChainService) HeadGenesisValidatorRoot() [32]byte {
return [32]byte{}
}
// VerifyBlkDescendant mocks VerifyBlkDescendant and always returns nil.
func (ms *ChainService) VerifyBlkDescendant(ctx context.Context, root [32]byte) error {
return ms.VerifyBlkDescendantErr
}

View File

@@ -1,4 +1,5 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
load("@prysm//tools/go:def.bzl", "go_library")
load("@io_bazel_rules_go//go:def.bzl", "go_test")
go_library(
name = "go_default_library",
@@ -6,16 +7,17 @@ go_library(
"attestation_data.go",
"checkpoint_state.go",
"committee.go",
"committee_ids.go",
"common.go",
"eth1_data.go",
"doc.go",
"hot_state_cache.go",
"skip_slot_cache.go",
"state_summary.go",
"subnet_ids.go",
],
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/cache",
visibility = [
"//beacon-chain:__subpackages__",
"//fuzz:__pkg__",
"//tools:__subpackages__",
],
deps = [
@@ -26,6 +28,7 @@ go_library(
"//shared/params:go_default_library",
"//shared/sliceutil:go_default_library",
"@com_github_hashicorp_golang_lru//:go_default_library",
"@com_github_patrickmn_go_cache//:go_default_library",
"@com_github_prometheus_client_golang//prometheus:go_default_library",
"@com_github_prometheus_client_golang//prometheus/promauto:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
@@ -41,12 +44,11 @@ go_test(
"attestation_data_test.go",
"checkpoint_state_test.go",
"committee_fuzz_test.go",
"committee_ids_test.go",
"committee_test.go",
"eth1_data_test.go",
"feature_flag_test.go",
"hot_state_cache_test.go",
"skip_slot_cache_test.go",
"subnet_ids_test.go",
],
embed = [":go_default_library"],
deps = [
@@ -56,6 +58,8 @@ go_test(
"//shared/featureconfig:go_default_library",
"//shared/hashutil:go_default_library",
"//shared/params:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_google_gofuzz//:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",

View File

@@ -11,6 +11,8 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"k8s.io/client-go/tools/cache"
)
@@ -97,6 +99,9 @@ func (c *AttestationCache) Get(ctx context.Context, req *ethpb.AttestationDataRe
if exists && item != nil && item.(*attestationReqResWrapper).res != nil {
attestationCacheHit.Inc()
if featureconfig.Get().ReduceAttesterStateCopy {
return state.CopyAttestationData(item.(*attestationReqResWrapper).res), nil
}
return item.(*attestationReqResWrapper).res, nil
}
attestationCacheMiss.Inc()
@@ -162,6 +167,9 @@ func wrapperToKey(i interface{}) (string, error) {
}
func reqToKey(req *ethpb.AttestationDataRequest) (string, error) {
if featureconfig.Get().ReduceAttesterStateCopy {
return fmt.Sprintf("%d", req.Slot), nil
}
return fmt.Sprintf("%d-%d", req.CommitteeIndex, req.Slot), nil
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
)
func TestAttestationCache_RoundTrip(t *testing.T) {
@@ -19,34 +20,20 @@ func TestAttestationCache_RoundTrip(t *testing.T) {
}
response, err := c.Get(ctx, req)
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
assert.Equal(t, (*ethpb.AttestationData)(nil), response)
if response != nil {
t.Errorf("Empty cache returned an object: %v", response)
}
if err := c.MarkInProgress(req); err != nil {
t.Error(err)
}
assert.NoError(t, c.MarkInProgress(req))
res := &ethpb.AttestationData{
Target: &ethpb.Checkpoint{Epoch: 5},
}
if err = c.Put(ctx, req, res); err != nil {
t.Error(err)
}
if err := c.MarkNotInProgress(req); err != nil {
t.Error(err)
}
assert.NoError(t, c.Put(ctx, req, res))
assert.NoError(t, c.MarkNotInProgress(req))
response, err = c.Get(ctx, req)
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
if !proto.Equal(response, res) {
t.Error("Expected equal protos to return from cache")

View File

@@ -20,7 +20,7 @@ var (
// maxCheckpointStateSize defines the max number of entries check point to state cache can contain.
// Choosing 10 to account for multiple forks, this allows 5 forks per epoch boundary with 2 epochs
// window to accept attestation based on latest spec.
maxCheckpointStateSize = 10
maxCheckpointStateSize = uint64(10)
// Metrics.
checkpointStateMiss = promauto.NewCounter(prometheus.CounterOpts{
@@ -93,7 +93,8 @@ func (c *CheckpointStateCache) StateByCheckpoint(cp *ethpb.Checkpoint) (*stateTr
return nil, ErrNotCheckpointState
}
return info.State.Copy(), nil
// Copy here is unnecessary since the return will only be used to verify attestation signature.
return info.State, nil
}
// AddCheckpointState adds CheckpointState object to the cache. This method also trims the least

View File

@@ -1,16 +1,17 @@
package cache
import (
"reflect"
"testing"
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/prysm/shared/params"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/hashutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestCheckpointStateCacheKeyFn_OK(t *testing.T) {
@@ -18,31 +19,23 @@ func TestCheckpointStateCacheKeyFn_OK(t *testing.T) {
st, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 64,
})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
info := &CheckpointState{
Checkpoint: cp,
State: st,
}
key, err := checkpointState(info)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
wantedKey, err := hashutil.HashProto(cp)
if err != nil {
t.Fatal(err)
}
if key != string(wantedKey[:]) {
t.Errorf("Incorrect hash key: %s, expected %s", key, string(wantedKey[:]))
}
require.NoError(t, err)
assert.Equal(t, string(wantedKey[:]), key)
}
func TestCheckpointStateCacheKeyFn_InvalidObj(t *testing.T) {
_, err := checkpointState("bad")
if err != ErrNotCheckpointState {
t.Errorf("Expected error %v, got %v", ErrNotCheckpointState, err)
}
assert.Equal(t, ErrNotCheckpointState, err)
}
func TestCheckpointStateCache_StateByCheckpoint(t *testing.T) {
@@ -53,28 +46,21 @@ func TestCheckpointStateCache_StateByCheckpoint(t *testing.T) {
GenesisValidatorsRoot: params.BeaconConfig().ZeroHash[:],
Slot: 64,
})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
info1 := &CheckpointState{
Checkpoint: cp1,
State: st,
}
state, err := cache.StateByCheckpoint(cp1)
if err != nil {
t.Fatal(err)
}
if state != nil {
t.Error("Expected state not to exist in empty cache")
}
require.NoError(t, err)
assert.Equal(t, (*stateTrie.BeaconState)(nil), state, "Expected state not to exist in empty cache")
require.NoError(t, cache.AddCheckpointState(info1))
if err := cache.AddCheckpointState(info1); err != nil {
t.Fatal(err)
}
state, err = cache.StateByCheckpoint(cp1)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if !proto.Equal(state.InnerStateUnsafe(), info1.State.InnerStateUnsafe()) {
t.Error("incorrectly cached state")
}
@@ -83,31 +69,21 @@ func TestCheckpointStateCache_StateByCheckpoint(t *testing.T) {
st2, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 128,
})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
info2 := &CheckpointState{
Checkpoint: cp2,
State: st2,
}
if err := cache.AddCheckpointState(info2); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.AddCheckpointState(info2))
state, err = cache.StateByCheckpoint(cp2)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(state.CloneInnerState(), info2.State.CloneInnerState()) {
t.Error("incorrectly cached state")
}
require.NoError(t, err)
assert.DeepEqual(t, info2.State.CloneInnerState(), state.CloneInnerState(), "incorrectly cached state")
state, err = cache.StateByCheckpoint(cp1)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(state.CloneInnerState(), info1.State.CloneInnerState()) {
t.Error("incorrectly cached state")
}
require.NoError(t, err)
assert.DeepEqual(t, info1.State.CloneInnerState(), state.CloneInnerState(), "incorrectly cached state")
}
func TestCheckpointStateCache_MaxSize(t *testing.T) {
@@ -115,27 +91,17 @@ func TestCheckpointStateCache_MaxSize(t *testing.T) {
st, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 0,
})
if err != nil {
t.Fatal(err)
}
for i := 0; i < maxCheckpointStateSize+100; i++ {
if err := st.SetSlot(uint64(i)); err != nil {
t.Fatal(err)
}
require.NoError(t, err)
for i := uint64(0); i < maxCheckpointStateSize+100; i++ {
require.NoError(t, st.SetSlot(i))
info := &CheckpointState{
Checkpoint: &ethpb.Checkpoint{Epoch: uint64(i)},
Checkpoint: &ethpb.Checkpoint{Epoch: i},
State: st,
}
if err := c.AddCheckpointState(info); err != nil {
t.Fatal(err)
}
require.NoError(t, c.AddCheckpointState(info))
}
if len(c.cache.ListKeys()) != maxCheckpointStateSize {
t.Errorf(
"Expected hash cache key size to be %d, got %d",
maxCheckpointStateSize,
len(c.cache.ListKeys()),
)
}
assert.Equal(t, maxCheckpointStateSize, uint64(len(c.cache.ListKeys())))
}

View File

@@ -19,7 +19,7 @@ var (
// maxCommitteesCacheSize defines the max number of shuffled committees on per randao basis can cache.
// Due to reorgs, it's good to keep the old cache around for quickly switch over. 10 is a generous
// cache size as it considers 3 concurrent branches over 3 epochs.
maxCommitteesCacheSize = 10
maxCommitteesCacheSize = uint64(10)
// CommitteeCacheMiss tracks the number of committee requests that aren't present in the cache.
CommitteeCacheMiss = promauto.NewCounter(prometheus.CounterOpts{
@@ -96,7 +96,7 @@ func (c *CommitteeCache) Committee(slot uint64, seed [32]byte, index uint64) ([]
indexOffSet := index + (slot%params.BeaconConfig().SlotsPerEpoch)*committeeCountPerSlot
start, end := startEndIndices(item, indexOffSet)
if int(end) > len(item.ShuffledIndices) || end < start {
if end > uint64(len(item.ShuffledIndices)) || end < start {
return nil, errors.New("requested index out of bound")
}
@@ -169,6 +169,30 @@ func (c *CommitteeCache) ActiveIndices(seed [32]byte) ([]uint64, error) {
return item.SortedIndices, nil
}
// ActiveIndicesCount returns the active indices count of a given seed stored in cache.
func (c *CommitteeCache) ActiveIndicesCount(seed [32]byte) (int, error) {
c.lock.RLock()
defer c.lock.RUnlock()
obj, exists, err := c.CommitteeCache.GetByKey(key(seed))
if err != nil {
return 0, err
}
if exists {
CommitteeCacheHit.Inc()
} else {
CommitteeCacheMiss.Inc()
return 0, nil
}
item, ok := obj.(*Committees)
if !ok {
return 0, ErrNotCommittee
}
return len(item.SortedIndices), nil
}
// ProposerIndices returns the proposer indices of a given seed.
func (c *CommitteeCache) ProposerIndices(seed [32]byte) ([]uint64, error) {
c.lock.RLock()

View File

@@ -1,10 +1,11 @@
package cache
import (
"reflect"
"testing"
fuzz "github.com/google/gofuzz"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestCommitteeKeyFuzz_OK(t *testing.T) {
@@ -14,12 +15,8 @@ func TestCommitteeKeyFuzz_OK(t *testing.T) {
for i := 0; i < 100000; i++ {
fuzzer.Fuzz(c)
k, err := committeeKeyFn(c)
if err != nil {
t.Fatal(err)
}
if k != key(c.Seed) {
t.Errorf("Incorrect hash k: %s, expected %s", k, key(c.Seed))
}
require.NoError(t, err)
assert.Equal(t, key(c.Seed), k)
}
}
@@ -30,17 +27,12 @@ func TestCommitteeCache_FuzzCommitteesByEpoch(t *testing.T) {
for i := 0; i < 100000; i++ {
fuzzer.Fuzz(c)
if err := cache.AddCommitteeShuffledList(c); err != nil {
t.Fatal(err)
}
if _, err := cache.Committee(0, c.Seed, 0); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.AddCommitteeShuffledList(c))
_, err := cache.Committee(0, c.Seed, 0)
require.NoError(t, err)
}
if len(cache.CommitteeCache.ListKeys()) != maxCommitteesCacheSize {
t.Error("Incorrect key size")
}
assert.Equal(t, maxCommitteesCacheSize, uint64(len(cache.CommitteeCache.ListKeys())), "Incorrect key size")
}
func TestCommitteeCache_FuzzActiveIndices(t *testing.T) {
@@ -50,19 +42,12 @@ func TestCommitteeCache_FuzzActiveIndices(t *testing.T) {
for i := 0; i < 100000; i++ {
fuzzer.Fuzz(c)
if err := cache.AddCommitteeShuffledList(c); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.AddCommitteeShuffledList(c))
indices, err := cache.ActiveIndices(c.Seed)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(indices, c.SortedIndices) {
t.Error("Saved indices not the same")
}
require.NoError(t, err)
assert.DeepEqual(t, c.SortedIndices, indices)
}
if len(cache.CommitteeCache.ListKeys()) != maxCommitteesCacheSize {
t.Error("Incorrect key size")
}
assert.Equal(t, maxCommitteesCacheSize, uint64(len(cache.CommitteeCache.ListKeys())), "Incorrect key size")
}

View File

@@ -1,87 +0,0 @@
package cache
import (
"sync"
lru "github.com/hashicorp/golang-lru"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/sliceutil"
)
type committeeIDs struct {
attester *lru.Cache
attesterLock sync.RWMutex
aggregator *lru.Cache
aggregatorLock sync.RWMutex
}
// CommitteeIDs for attester and aggregator.
var CommitteeIDs = newCommitteeIDs()
func newCommitteeIDs() *committeeIDs {
// Given a node can calculate committee assignments of current epoch and next epoch.
// Max size is set to 2 epoch length.
cacheSize := int(params.BeaconConfig().MaxCommitteesPerSlot * params.BeaconConfig().SlotsPerEpoch * 2)
attesterCache, err := lru.New(cacheSize)
if err != nil {
panic(err)
}
aggregatorCache, err := lru.New(cacheSize)
if err != nil {
panic(err)
}
return &committeeIDs{attester: attesterCache, aggregator: aggregatorCache}
}
// AddAttesterCommiteeID adds committee ID for subscribing subnet for the attester of a given slot.
func (c *committeeIDs) AddAttesterCommiteeID(slot uint64, committeeID uint64) {
c.attesterLock.Lock()
defer c.attesterLock.Unlock()
ids := []uint64{committeeID}
val, exists := c.attester.Get(slot)
if exists {
ids = sliceutil.UnionUint64(append(val.([]uint64), ids...))
}
c.attester.Add(slot, ids)
}
// GetAttesterCommitteeIDs gets the committee ID for subscribing subnet for attester of the slot.
func (c *committeeIDs) GetAttesterCommitteeIDs(slot uint64) []uint64 {
c.attesterLock.RLock()
defer c.attesterLock.RUnlock()
val, exists := c.attester.Get(slot)
if !exists {
return nil
}
if v, ok := val.([]uint64); ok {
return v
}
return nil
}
// AddAggregatorCommiteeID adds committee ID for subscribing subnet for the aggregator of a given slot.
func (c *committeeIDs) AddAggregatorCommiteeID(slot uint64, committeeID uint64) {
c.aggregatorLock.Lock()
defer c.aggregatorLock.Unlock()
ids := []uint64{committeeID}
val, exists := c.aggregator.Get(slot)
if exists {
ids = sliceutil.UnionUint64(append(val.([]uint64), ids...))
}
c.aggregator.Add(slot, ids)
}
// GetAggregatorCommitteeIDs gets the committee ID for subscribing subnet for aggregator of the slot.
func (c *committeeIDs) GetAggregatorCommitteeIDs(slot uint64) []uint64 {
c.aggregatorLock.RLock()
defer c.aggregatorLock.RUnlock()
val, exists := c.aggregator.Get(slot)
if !exists {
return []uint64{}
}
return val.([]uint64)
}

View File

@@ -1,56 +0,0 @@
package cache
import (
"reflect"
"testing"
)
func TestCommitteeIDCache_RoundTrip(t *testing.T) {
c := newCommitteeIDs()
slot := uint64(100)
committeeIDs := c.GetAggregatorCommitteeIDs(slot)
if len(committeeIDs) != 0 {
t.Errorf("Empty cache returned an object: %v", committeeIDs)
}
c.AddAggregatorCommiteeID(slot, 1)
res := c.GetAggregatorCommitteeIDs(slot)
if !reflect.DeepEqual(res, []uint64{1}) {
t.Error("Expected equal value to return from cache")
}
c.AddAggregatorCommiteeID(slot, 2)
res = c.GetAggregatorCommitteeIDs(slot)
if !reflect.DeepEqual(res, []uint64{1, 2}) {
t.Error("Expected equal value to return from cache")
}
c.AddAggregatorCommiteeID(slot, 3)
res = c.GetAggregatorCommitteeIDs(slot)
if !reflect.DeepEqual(res, []uint64{1, 2, 3}) {
t.Error("Expected equal value to return from cache")
}
committeeIDs = c.GetAttesterCommitteeIDs(slot)
if len(committeeIDs) != 0 {
t.Errorf("Empty cache returned an object: %v", committeeIDs)
}
c.AddAttesterCommiteeID(slot, 11)
res = c.GetAttesterCommitteeIDs(slot)
if !reflect.DeepEqual(res, []uint64{11}) {
t.Error("Expected equal value to return from cache")
}
c.AddAttesterCommiteeID(slot, 22)
res = c.GetAttesterCommitteeIDs(slot)
if !reflect.DeepEqual(res, []uint64{11, 22}) {
t.Error("Expected equal value to return from cache")
}
c.AddAttesterCommiteeID(slot, 33)
res = c.GetAttesterCommitteeIDs(slot)
if !reflect.DeepEqual(res, []uint64{11, 22, 33}) {
t.Error("Expected equal value to return from cache")
}
}

View File

@@ -2,13 +2,14 @@ package cache
import (
"math"
"reflect"
"sort"
"strconv"
"testing"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestCommitteeKeyFn_OK(t *testing.T) {
@@ -19,19 +20,13 @@ func TestCommitteeKeyFn_OK(t *testing.T) {
}
k, err := committeeKeyFn(item)
if err != nil {
t.Fatal(err)
}
if k != key(item.Seed) {
t.Errorf("Incorrect hash k: %s, expected %s", k, key(item.Seed))
}
require.NoError(t, err)
assert.Equal(t, key(item.Seed), k)
}
func TestCommitteeKeyFn_InvalidObj(t *testing.T) {
_, err := committeeKeyFn("bad")
if err != ErrNotCommittee {
t.Errorf("Expected error %v, got %v", ErrNotCommittee, err)
}
assert.Equal(t, ErrNotCommittee, err)
}
func TestCommitteeCache_CommitteesByEpoch(t *testing.T) {
@@ -46,30 +41,18 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) {
slot := params.BeaconConfig().SlotsPerEpoch
committeeIndex := uint64(1)
indices, err := cache.Committee(slot, item.Seed, committeeIndex)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if indices != nil {
t.Error("Expected committee not to exist in empty cache")
}
require.NoError(t, cache.AddCommitteeShuffledList(item))
if err := cache.AddCommitteeShuffledList(item); err != nil {
t.Fatal(err)
}
wantedIndex := uint64(0)
indices, err = cache.Committee(slot, item.Seed, wantedIndex)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
start, end := startEndIndices(item, wantedIndex)
if !reflect.DeepEqual(indices, item.ShuffledIndices[start:end]) {
t.Errorf(
"Expected fetched active indices to be %v, got %v",
indices,
item.ShuffledIndices[start:end],
)
}
assert.DeepEqual(t, item.ShuffledIndices[start:end], indices)
}
func TestCommitteeCache_ActiveIndices(t *testing.T) {
@@ -77,24 +60,31 @@ func TestCommitteeCache_ActiveIndices(t *testing.T) {
item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []uint64{1, 2, 3, 4, 5, 6}}
indices, err := cache.ActiveIndices(item.Seed)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if indices != nil {
t.Error("Expected committee count not to exist in empty cache")
t.Error("Expected committee not to exist in empty cache")
}
if err := cache.AddCommitteeShuffledList(item); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.AddCommitteeShuffledList(item))
indices, err = cache.ActiveIndices(item.Seed)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(indices, item.SortedIndices) {
t.Error("Did not receive correct active indices from cache")
}
require.NoError(t, err)
assert.DeepEqual(t, item.SortedIndices, indices)
}
func TestCommitteeCache_ActiveCount(t *testing.T) {
cache := NewCommitteesCache()
item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []uint64{1, 2, 3, 4, 5, 6}}
count, err := cache.ActiveIndicesCount(item.Seed)
require.NoError(t, err)
assert.Equal(t, 0, count, "Expected active count not to exist in empty cache")
require.NoError(t, cache.AddCommitteeShuffledList(item))
count, err = cache.ActiveIndicesCount(item.Seed)
require.NoError(t, err)
assert.Equal(t, len(item.SortedIndices), count)
}
func TestCommitteeCache_AddProposerIndicesList(t *testing.T) {
@@ -103,45 +93,29 @@ func TestCommitteeCache_AddProposerIndicesList(t *testing.T) {
seed := [32]byte{'A'}
indices := []uint64{1, 2, 3, 4, 5}
indices, err := cache.ProposerIndices(seed)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if indices != nil {
t.Error("Expected committee count not to exist in empty cache")
}
if err := cache.AddProposerIndicesList(seed, indices); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.AddProposerIndicesList(seed, indices))
received, err := cache.ProposerIndices(seed)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(indices, received) {
t.Error("Did not receive correct proposer indices from cache")
}
require.NoError(t, err)
assert.DeepEqual(t, received, indices)
item := &Committees{Seed: [32]byte{'B'}, SortedIndices: []uint64{1, 2, 3, 4, 5, 6}}
if err := cache.AddCommitteeShuffledList(item); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.AddCommitteeShuffledList(item))
indices, err = cache.ProposerIndices(item.Seed)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if indices != nil {
t.Error("Expected committee count not to exist in empty cache")
}
if err := cache.AddProposerIndicesList(item.Seed, indices); err != nil {
t.Fatal(err)
}
received, err = cache.ProposerIndices(item.Seed)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(indices, received) {
t.Error("Did not receive correct proposer indices from cache")
}
require.NoError(t, cache.AddProposerIndicesList(item.Seed, indices))
received, err = cache.ProposerIndices(item.Seed)
require.NoError(t, err)
assert.DeepEqual(t, received, indices)
}
func TestCommitteeCache_CanRotate(t *testing.T) {
@@ -151,27 +125,20 @@ func TestCommitteeCache_CanRotate(t *testing.T) {
for i := 100; i < 200; i++ {
s := []byte(strconv.Itoa(i))
item := &Committees{Seed: bytesutil.ToBytes32(s)}
if err := cache.AddCommitteeShuffledList(item); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.AddCommitteeShuffledList(item))
}
k := cache.CommitteeCache.ListKeys()
if len(k) != maxCommitteesCacheSize {
t.Errorf("wanted: %d, got: %d", maxCommitteesCacheSize, len(k))
}
assert.Equal(t, maxCommitteesCacheSize, uint64(len(k)))
sort.Slice(k, func(i, j int) bool {
return k[i] < k[j]
})
s := bytesutil.ToBytes32([]byte(strconv.Itoa(190)))
if k[0] != key(s) {
t.Error("incorrect key received for slot 190")
}
assert.Equal(t, key(s), k[0], "incorrect key received for slot 190")
s = bytesutil.ToBytes32([]byte(strconv.Itoa(199)))
if k[len(k)-1] != key(s) {
t.Error("incorrect key received for slot 199")
}
assert.Equal(t, key(s), k[len(k)-1], "incorrect key received for slot 199")
}
func TestCommitteeCacheOutOfRange(t *testing.T) {
@@ -184,11 +151,8 @@ func TestCommitteeCacheOutOfRange(t *testing.T) {
SortedIndices: []uint64{},
ProposerIndices: []uint64{},
})
if err != nil {
t.Error(err)
}
require.NoError(t, err)
_, err = cache.Committee(0, seed, math.MaxUint64) // Overflow!
if err == nil {
t.Fatal("Did not fail as expected")
}
require.NotNil(t, err, "Did not fail as expected")
}

View File

@@ -8,12 +8,12 @@ import (
var (
// maxCacheSize is 4x of the epoch length for additional cache padding.
// Requests should be only accessing committees within defined epoch length.
maxCacheSize = int(4 * params.BeaconConfig().SlotsPerEpoch)
maxCacheSize = 4 * params.BeaconConfig().SlotsPerEpoch
)
// trim the FIFO queue to the maxSize.
func trim(queue *cache.FIFO, maxSize int) {
for s := len(queue.ListKeys()); s > maxSize; s-- {
func trim(queue *cache.FIFO, maxSize uint64) {
for s := uint64(len(queue.ListKeys())); s > maxSize; s-- {
_, err := queue.Pop(popProcessNoopFunc)
if err != nil {
// popProcessNoopFunc never returns an error, but we handle this anyway to make linter

View File

@@ -1,4 +1,5 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
load("@prysm//tools/go:def.bzl", "go_library")
load("@io_bazel_rules_go//go:def.bzl", "go_test")
go_library(
name = "go_default_library",
@@ -12,9 +13,12 @@ go_library(
"//proto/beacon/db:go_default_library",
"//shared/bytesutil:go_default_library",
"//shared/hashutil:go_default_library",
"//shared/params:go_default_library",
"//shared/trieutil:go_default_library",
"@com_github_prometheus_client_golang//prometheus:go_default_library",
"@com_github_prometheus_client_golang//prometheus/promauto:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_prysmaticlabs_go_ssz//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@io_opencensus_go//trace:go_default_library",
],
@@ -23,15 +27,20 @@ go_library(
go_test(
name = "go_default_test",
srcs = [
"deposits_test.go",
"deposits_cache_test.go",
"pending_deposits_test.go",
],
embed = [":go_default_library"],
deps = [
"//proto/beacon/db:go_default_library",
"//shared/bytesutil:go_default_library",
"//shared/params:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"//shared/trieutil:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@com_github_prysmaticlabs_go_ssz//:go_default_library",
"@com_github_sirupsen_logrus//hooks/test:go_default_library",
],
)

View File

@@ -1,3 +1,7 @@
// Package depositcache is the source of validator deposits maintained
// in-memory by the beacon node deposits processed from the
// eth1 powchain are then stored in this cache to be accessed by
// any other service during a beacon node's runtime.
package depositcache
import (
@@ -11,8 +15,11 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
dbpb "github.com/prysmaticlabs/prysm/proto/beacon/db"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/trieutil"
log "github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
@@ -26,31 +33,48 @@ var (
// DepositFetcher defines a struct which can retrieve deposit information from a store.
type DepositFetcher interface {
AllDeposits(ctx context.Context, beforeBlk *big.Int) []*ethpb.Deposit
AllDeposits(ctx context.Context, untilBlk *big.Int) []*ethpb.Deposit
DepositByPubkey(ctx context.Context, pubKey []byte) (*ethpb.Deposit, *big.Int)
DepositsNumberAndRootAtHeight(ctx context.Context, blockHeight *big.Int) (uint64, [32]byte)
FinalizedDeposits(ctx context.Context) *FinalizedDeposits
NonFinalizedDeposits(ctx context.Context, untilBlk *big.Int) []*ethpb.Deposit
}
// FinalizedDeposits stores the trie of deposits that have been included
// in the beacon state up to the latest finalized checkpoint.
type FinalizedDeposits struct {
Deposits *trieutil.SparseMerkleTrie
MerkleTrieIndex int64
}
// DepositCache stores all in-memory deposit objects. This
// stores all the deposit related data that is required by the beacon-node.
type DepositCache struct {
// Beacon chain deposits in memory.
pendingDeposits []*dbpb.DepositContainer
deposits []*dbpb.DepositContainer
depositsLock sync.RWMutex
chainStartDeposits []*ethpb.Deposit
chainstartPubkeys map[string]bool
chainstartPubkeysLock sync.RWMutex
pendingDeposits []*dbpb.DepositContainer
deposits []*dbpb.DepositContainer
finalizedDeposits *FinalizedDeposits
depositsLock sync.RWMutex
chainStartDeposits []*ethpb.Deposit
chainStartPubkeys map[string]bool
}
// NewDepositCache instantiates a new deposit cache
func NewDepositCache() *DepositCache {
func NewDepositCache() (*DepositCache, error) {
finalizedDepositsTrie, err := trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth))
if err != nil {
return nil, err
}
// finalizedDeposits.MerkleTrieIndex is initialized to -1 because it represents the index of the last trie item.
// Inserting the first item into the trie will set the value of the index to 0.
return &DepositCache{
pendingDeposits: []*dbpb.DepositContainer{},
deposits: []*dbpb.DepositContainer{},
chainstartPubkeys: make(map[string]bool),
finalizedDeposits: &FinalizedDeposits{Deposits: finalizedDepositsTrie, MerkleTrieIndex: -1},
chainStartPubkeys: make(map[string]bool),
chainStartDeposits: make([]*ethpb.Deposit, 0),
}
}, nil
}
// InsertDeposit into the database. If deposit or block number are nil
@@ -69,7 +93,7 @@ func (dc *DepositCache) InsertDeposit(ctx context.Context, d *ethpb.Deposit, blo
}
dc.depositsLock.Lock()
defer dc.depositsLock.Unlock()
// keep the slice sorted on insertion in order to avoid costly sorting on retrival.
// Keep the slice sorted on insertion in order to avoid costly sorting on retrieval.
heightIdx := sort.Search(len(dc.deposits), func(i int) bool { return dc.deposits[i].Index >= index })
newDeposits := append([]*dbpb.DepositContainer{{Deposit: d, Eth1BlockHeight: blockNum, DepositRoot: depositRoot[:], Index: index}}, dc.deposits[heightIdx:]...)
dc.deposits = append(dc.deposits[:heightIdx], newDeposits...)
@@ -88,9 +112,40 @@ func (dc *DepositCache) InsertDepositContainers(ctx context.Context, ctrs []*dbp
historicalDepositsCount.Add(float64(len(ctrs)))
}
// AllDepositContainers returns a list of deposits all historical deposit containers until the given block number.
// InsertFinalizedDeposits inserts deposits up to eth1DepositIndex (inclusive) into the finalized deposits cache.
func (dc *DepositCache) InsertFinalizedDeposits(ctx context.Context, eth1DepositIndex int64) {
ctx, span := trace.StartSpan(ctx, "DepositsCache.InsertFinalizedDeposits")
defer span.End()
dc.depositsLock.Lock()
defer dc.depositsLock.Unlock()
depositTrie := dc.finalizedDeposits.Deposits
insertIndex := dc.finalizedDeposits.MerkleTrieIndex + 1
for _, d := range dc.deposits {
if d.Index <= dc.finalizedDeposits.MerkleTrieIndex {
continue
}
if d.Index > eth1DepositIndex {
break
}
depHash, err := ssz.HashTreeRoot(d.Deposit.Data)
if err != nil {
log.WithError(err).Error("Could not hash deposit data. Finalized deposit cache not updated.")
return
}
depositTrie.Insert(depHash[:], int(insertIndex))
insertIndex++
}
dc.finalizedDeposits = &FinalizedDeposits{
Deposits: depositTrie,
MerkleTrieIndex: eth1DepositIndex,
}
}
// AllDepositContainers returns all historical deposit containers.
func (dc *DepositCache) AllDepositContainers(ctx context.Context) []*dbpb.DepositContainer {
ctx, span := trace.StartSpan(ctx, "BeaconDB.AllDepositContainers")
ctx, span := trace.StartSpan(ctx, "DepositsCache.AllDepositContainers")
defer span.End()
dc.depositsLock.RLock()
defer dc.depositsLock.RUnlock()
@@ -102,27 +157,23 @@ func (dc *DepositCache) AllDepositContainers(ctx context.Context) []*dbpb.Deposi
func (dc *DepositCache) MarkPubkeyForChainstart(ctx context.Context, pubkey string) {
ctx, span := trace.StartSpan(ctx, "DepositsCache.MarkPubkeyForChainstart")
defer span.End()
dc.chainstartPubkeysLock.Lock()
defer dc.chainstartPubkeysLock.Unlock()
dc.chainstartPubkeys[pubkey] = true
dc.chainStartPubkeys[pubkey] = true
}
// PubkeyInChainstart returns bool for whether the pubkey passed in has deposited.
func (dc *DepositCache) PubkeyInChainstart(ctx context.Context, pubkey string) bool {
ctx, span := trace.StartSpan(ctx, "DepositsCache.PubkeyInChainstart")
defer span.End()
dc.chainstartPubkeysLock.Lock()
defer dc.chainstartPubkeysLock.Unlock()
if dc.chainstartPubkeys != nil {
return dc.chainstartPubkeys[pubkey]
if dc.chainStartPubkeys != nil {
return dc.chainStartPubkeys[pubkey]
}
dc.chainstartPubkeys = make(map[string]bool)
dc.chainStartPubkeys = make(map[string]bool)
return false
}
// AllDeposits returns a list of deposits all historical deposits until the given block number
// AllDeposits returns a list of historical deposits until the given block number
// (inclusive). If no block is specified then this method returns all historical deposits.
func (dc *DepositCache) AllDeposits(ctx context.Context, beforeBlk *big.Int) []*ethpb.Deposit {
func (dc *DepositCache) AllDeposits(ctx context.Context, untilBlk *big.Int) []*ethpb.Deposit {
ctx, span := trace.StartSpan(ctx, "DepositsCache.AllDeposits")
defer span.End()
dc.depositsLock.RLock()
@@ -130,7 +181,7 @@ func (dc *DepositCache) AllDeposits(ctx context.Context, beforeBlk *big.Int) []*
var deposits []*ethpb.Deposit
for _, ctnr := range dc.deposits {
if beforeBlk == nil || beforeBlk.Uint64() >= ctnr.Eth1BlockHeight {
if untilBlk == nil || untilBlk.Uint64() >= ctnr.Eth1BlockHeight {
deposits = append(deposits, ctnr.Deposit)
}
}
@@ -172,3 +223,39 @@ func (dc *DepositCache) DepositByPubkey(ctx context.Context, pubKey []byte) (*et
}
return deposit, blockNum
}
// FinalizedDeposits returns the finalized deposits trie.
func (dc *DepositCache) FinalizedDeposits(ctx context.Context) *FinalizedDeposits {
ctx, span := trace.StartSpan(ctx, "DepositsCache.FinalizedDeposits")
defer span.End()
dc.depositsLock.RLock()
defer dc.depositsLock.RUnlock()
return &FinalizedDeposits{
Deposits: dc.finalizedDeposits.Deposits.Copy(),
MerkleTrieIndex: dc.finalizedDeposits.MerkleTrieIndex,
}
}
// NonFinalizedDeposits returns the list of non-finalized deposits until the given block number (inclusive).
// If no block is specified then this method returns all non-finalized deposits.
func (dc *DepositCache) NonFinalizedDeposits(ctx context.Context, untilBlk *big.Int) []*ethpb.Deposit {
ctx, span := trace.StartSpan(ctx, "DepositsCache.NonFinalizedDeposits")
defer span.End()
dc.depositsLock.RLock()
defer dc.depositsLock.RUnlock()
if dc.finalizedDeposits == nil {
return dc.AllDeposits(ctx, untilBlk)
}
lastFinalizedDepositIndex := dc.finalizedDeposits.MerkleTrieIndex
var deposits []*ethpb.Deposit
for _, d := range dc.deposits {
if (d.Index > lastFinalizedDepositIndex) && (untilBlk == nil || untilBlk.Uint64() >= d.Eth1BlockHeight) {
deposits = append(deposits, d.Deposit)
}
}
return deposits
}

View File

@@ -0,0 +1,483 @@
package depositcache
import (
"bytes"
"context"
"fmt"
"math/big"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
dbpb "github.com/prysmaticlabs/prysm/proto/beacon/db"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/shared/trieutil"
logTest "github.com/sirupsen/logrus/hooks/test"
)
const nilDepositErr = "Ignoring nil deposit insertion"
var _ = DepositFetcher(&DepositCache{})
func TestInsertDeposit_LogsOnNilDepositInsertion(t *testing.T) {
hook := logTest.NewGlobal()
dc, err := NewDepositCache()
require.NoError(t, err)
dc.InsertDeposit(context.Background(), nil, 1, 0, [32]byte{})
require.Equal(t, 0, len(dc.deposits), "Number of deposits changed")
assert.Equal(t, nilDepositErr, hook.LastEntry().Message)
}
func TestInsertDeposit_MaintainsSortedOrderByIndex(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
insertions := []struct {
blkNum uint64
deposit *ethpb.Deposit
index int64
}{
{
blkNum: 0,
deposit: &ethpb.Deposit{},
index: 0,
},
{
blkNum: 0,
deposit: &ethpb.Deposit{},
index: 3,
},
{
blkNum: 0,
deposit: &ethpb.Deposit{},
index: 1,
},
{
blkNum: 0,
deposit: &ethpb.Deposit{},
index: 4,
},
}
for _, ins := range insertions {
dc.InsertDeposit(context.Background(), ins.deposit, ins.blkNum, ins.index, [32]byte{})
}
expectedIndices := []int64{0, 1, 3, 4}
for i, ei := range expectedIndices {
assert.Equal(t, ei, dc.deposits[i].Index,
fmt.Sprintf("dc.deposits[%d].Index = %d, wanted %d", i, dc.deposits[i].Index, ei))
}
}
func TestAllDeposits_ReturnsAllDeposits(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
deposits := []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
}
dc.deposits = deposits
d := dc.AllDeposits(context.Background(), nil)
assert.Equal(t, len(deposits), len(d))
}
func TestAllDeposits_FiltersDepositUpToAndIncludingBlockNumber(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
deposits := []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
}
dc.deposits = deposits
d := dc.AllDeposits(context.Background(), big.NewInt(11))
assert.Equal(t, 5, len(d))
}
func TestDepositsNumberAndRootAtHeight_ReturnsAppropriateCountAndRoot(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
dc.deposits = []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
DepositRoot: []byte("root"),
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
}
n, root := dc.DepositsNumberAndRootAtHeight(context.Background(), big.NewInt(11))
assert.Equal(t, 5, int(n))
assert.Equal(t, bytesutil.ToBytes32([]byte("root")), root)
}
func TestDepositsNumberAndRootAtHeight_ReturnsEmptyTrieIfBlockHeightLessThanOldestDeposit(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
dc.deposits = []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
DepositRoot: []byte("root"),
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
DepositRoot: []byte("root"),
},
}
n, root := dc.DepositsNumberAndRootAtHeight(context.Background(), big.NewInt(2))
assert.Equal(t, 0, int(n))
assert.Equal(t, [32]byte{}, root)
}
func TestDepositByPubkey_ReturnsFirstMatchingDeposit(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
dc.deposits = []*dbpb.DepositContainer{
{
Eth1BlockHeight: 9,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte("pk0"),
},
},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte("pk1"),
},
},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte("pk1"),
},
},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte("pk2"),
},
},
},
}
dep, blkNum := dc.DepositByPubkey(context.Background(), []byte("pk1"))
if !bytes.Equal(dep.Data.PublicKey, []byte("pk1")) {
t.Error("Returned wrong deposit")
}
assert.Equal(t, 0, blkNum.Cmp(big.NewInt(10)),
fmt.Sprintf("Returned wrong block number %v", blkNum))
}
func TestFinalizedDeposits_DepositsCachedCorrectly(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
finalizedDeposits := []*dbpb.DepositContainer{
{
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{0},
},
},
Index: 0,
},
{
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{1},
},
},
Index: 1,
},
{
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{2},
},
},
Index: 2,
},
}
dc.deposits = append(finalizedDeposits, &dbpb.DepositContainer{
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{3},
},
},
Index: 3,
})
dc.InsertFinalizedDeposits(context.Background(), 2)
cachedDeposits := dc.FinalizedDeposits(context.Background())
require.NotNil(t, cachedDeposits, "Deposits not cached")
assert.Equal(t, int64(2), cachedDeposits.MerkleTrieIndex)
var deps [][]byte
for _, d := range finalizedDeposits {
hash, err := ssz.HashTreeRoot(d.Deposit.Data)
require.NoError(t, err, "Could not hash deposit data")
deps = append(deps, hash[:])
}
trie, err := trieutil.GenerateTrieFromItems(deps, int(params.BeaconConfig().DepositContractTreeDepth))
require.NoError(t, err, "Could not generate deposit trie")
assert.Equal(t, trie.HashTreeRoot(), cachedDeposits.Deposits.HashTreeRoot())
}
func TestFinalizedDeposits_UtilizesPreviouslyCachedDeposits(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
oldFinalizedDeposits := []*dbpb.DepositContainer{
{
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{0},
},
},
Index: 0,
},
{
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{1},
},
},
Index: 1,
},
}
newFinalizedDeposit := dbpb.DepositContainer{
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{2},
},
},
Index: 2,
}
dc.deposits = oldFinalizedDeposits
dc.InsertFinalizedDeposits(context.Background(), 1)
// Artificially exclude old deposits so that they can only be retrieved from previously finalized deposits.
dc.deposits = []*dbpb.DepositContainer{&newFinalizedDeposit}
dc.InsertFinalizedDeposits(context.Background(), 2)
cachedDeposits := dc.FinalizedDeposits(context.Background())
require.NotNil(t, cachedDeposits, "Deposits not cached")
assert.Equal(t, int64(2), cachedDeposits.MerkleTrieIndex)
var deps [][]byte
for _, d := range append(oldFinalizedDeposits, &newFinalizedDeposit) {
hash, err := ssz.HashTreeRoot(d.Deposit.Data)
require.NoError(t, err, "Could not hash deposit data")
deps = append(deps, hash[:])
}
trie, err := trieutil.GenerateTrieFromItems(deps, int(params.BeaconConfig().DepositContractTreeDepth))
require.NoError(t, err, "Could not generate deposit trie")
assert.Equal(t, trie.HashTreeRoot(), cachedDeposits.Deposits.HashTreeRoot())
}
func TestFinalizedDeposits_InitializedCorrectly(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
finalizedDeposits := dc.finalizedDeposits
assert.NotNil(t, finalizedDeposits)
assert.NotNil(t, finalizedDeposits.Deposits)
assert.Equal(t, int64(-1), finalizedDeposits.MerkleTrieIndex)
}
func TestNonFinalizedDeposits_ReturnsAllNonFinalizedDeposits(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
finalizedDeposits := []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{0},
},
},
Index: 0,
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{1},
},
},
Index: 1,
},
}
dc.deposits = append(finalizedDeposits,
&dbpb.DepositContainer{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{2},
},
},
Index: 2,
},
&dbpb.DepositContainer{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{3},
},
},
Index: 3,
})
dc.InsertFinalizedDeposits(context.Background(), 1)
deps := dc.NonFinalizedDeposits(context.Background(), nil)
assert.Equal(t, 2, len(deps))
}
func TestNonFinalizedDeposits_ReturnsNonFinalizedDepositsUpToBlockNumber(t *testing.T) {
dc, err := NewDepositCache()
require.NoError(t, err)
finalizedDeposits := []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{0},
},
},
Index: 0,
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{1},
},
},
Index: 1,
},
}
dc.deposits = append(finalizedDeposits,
&dbpb.DepositContainer{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{2},
},
},
Index: 2,
},
&dbpb.DepositContainer{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{3},
},
},
Index: 3,
})
dc.InsertFinalizedDeposits(context.Background(), 1)
deps := dc.NonFinalizedDeposits(context.Background(), big.NewInt(10))
assert.Equal(t, 1, len(deps))
}

View File

@@ -1,275 +0,0 @@
package depositcache
import (
"bytes"
"context"
"math/big"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
dbpb "github.com/prysmaticlabs/prysm/proto/beacon/db"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
logTest "github.com/sirupsen/logrus/hooks/test"
)
const nilDepositErr = "Ignoring nil deposit insertion"
var _ = DepositFetcher(&DepositCache{})
func TestBeaconDB_InsertDeposit_LogsOnNilDepositInsertion(t *testing.T) {
hook := logTest.NewGlobal()
dc := DepositCache{}
dc.InsertDeposit(context.Background(), nil, 1, 0, [32]byte{})
if len(dc.deposits) != 0 {
t.Fatal("Number of deposits changed")
}
if hook.LastEntry().Message != nilDepositErr {
t.Errorf("Did not log correct message, wanted \"Ignoring nil deposit insertion\", got \"%s\"", hook.LastEntry().Message)
}
}
func TestBeaconDB_InsertDeposit_MaintainsSortedOrderByIndex(t *testing.T) {
dc := DepositCache{}
insertions := []struct {
blkNum uint64
deposit *ethpb.Deposit
index int64
}{
{
blkNum: 0,
deposit: &ethpb.Deposit{},
index: 0,
},
{
blkNum: 0,
deposit: &ethpb.Deposit{},
index: 3,
},
{
blkNum: 0,
deposit: &ethpb.Deposit{},
index: 1,
},
{
blkNum: 0,
deposit: &ethpb.Deposit{},
index: 4,
},
}
for _, ins := range insertions {
dc.InsertDeposit(context.Background(), ins.deposit, ins.blkNum, ins.index, [32]byte{})
}
expectedIndices := []int64{0, 1, 3, 4}
for i, ei := range expectedIndices {
if dc.deposits[i].Index != ei {
t.Errorf("dc.deposits[%d].Index = %d, wanted %d", i, dc.deposits[i].Index, ei)
}
}
}
func TestBeaconDB_AllDeposits_ReturnsAllDeposits(t *testing.T) {
dc := DepositCache{}
deposits := []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
}
dc.deposits = deposits
d := dc.AllDeposits(context.Background(), nil)
if len(d) != len(deposits) {
t.Errorf("Return the wrong number of deposits (%d) wanted %d", len(d), len(deposits))
}
}
func TestBeaconDB_AllDeposits_FiltersDepositUpToAndIncludingBlockNumber(t *testing.T) {
dc := DepositCache{}
deposits := []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
}
dc.deposits = deposits
d := dc.AllDeposits(context.Background(), big.NewInt(11))
expected := 5
if len(d) != expected {
t.Errorf("Return the wrong number of deposits (%d) wanted %d", len(d), expected)
}
}
func TestBeaconDB_DepositsNumberAndRootAtHeight_ReturnsAppropriateCountAndRoot(t *testing.T) {
dc := DepositCache{}
dc.deposits = []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
DepositRoot: []byte("root"),
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{},
},
}
n, root := dc.DepositsNumberAndRootAtHeight(context.Background(), big.NewInt(11))
if int(n) != 5 {
t.Errorf("Returned unexpected deposits number %d wanted %d", n, 5)
}
if root != bytesutil.ToBytes32([]byte("root")) {
t.Errorf("Returned unexpected root: %v", root)
}
}
func TestBeaconDB_DepositsNumberAndRootAtHeight_ReturnsEmptyTrieIfBlockHeightLessThanOldestDeposit(t *testing.T) {
dc := DepositCache{}
dc.deposits = []*dbpb.DepositContainer{
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{},
DepositRoot: []byte("root"),
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{},
DepositRoot: []byte("root"),
},
}
n, root := dc.DepositsNumberAndRootAtHeight(context.Background(), big.NewInt(2))
if int(n) != 0 {
t.Errorf("Returned unexpected deposits number %d wanted %d", n, 0)
}
if root != [32]byte{} {
t.Errorf("Returned unexpected root: %v", root)
}
}
func TestBeaconDB_DepositByPubkey_ReturnsFirstMatchingDeposit(t *testing.T) {
dc := DepositCache{}
dc.deposits = []*dbpb.DepositContainer{
{
Eth1BlockHeight: 9,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte("pk0"),
},
},
},
{
Eth1BlockHeight: 10,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte("pk1"),
},
},
},
{
Eth1BlockHeight: 11,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte("pk1"),
},
},
},
{
Eth1BlockHeight: 12,
Deposit: &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte("pk2"),
},
},
},
}
dep, blkNum := dc.DepositByPubkey(context.Background(), []byte("pk1"))
if !bytes.Equal(dep.Data.PublicKey, []byte("pk1")) {
t.Error("Returned wrong deposit")
}
if blkNum.Cmp(big.NewInt(10)) != 0 {
t.Errorf("Returned wrong block number %v", blkNum)
}
}

View File

@@ -24,7 +24,7 @@ var (
// PendingDepositsFetcher specifically outlines a struct that can retrieve deposits
// which have not yet been included in the chain.
type PendingDepositsFetcher interface {
PendingContainers(ctx context.Context, beforeBlk *big.Int) []*dbpb.DepositContainer
PendingContainers(ctx context.Context, untilBlk *big.Int) []*dbpb.DepositContainer
}
// InsertPendingDeposit into the database. If deposit or block number are nil
@@ -50,36 +50,23 @@ func (dc *DepositCache) InsertPendingDeposit(ctx context.Context, d *ethpb.Depos
// PendingDeposits returns a list of deposits until the given block number
// (inclusive). If no block is specified then this method returns all pending
// deposits.
func (dc *DepositCache) PendingDeposits(ctx context.Context, beforeBlk *big.Int) []*ethpb.Deposit {
func (dc *DepositCache) PendingDeposits(ctx context.Context, untilBlk *big.Int) []*ethpb.Deposit {
ctx, span := trace.StartSpan(ctx, "DepositsCache.PendingDeposits")
defer span.End()
dc.depositsLock.RLock()
defer dc.depositsLock.RUnlock()
var depositCntrs []*dbpb.DepositContainer
for _, ctnr := range dc.pendingDeposits {
if beforeBlk == nil || beforeBlk.Uint64() >= ctnr.Eth1BlockHeight {
depositCntrs = append(depositCntrs, ctnr)
}
}
// Sort the deposits by Merkle index.
sort.SliceStable(depositCntrs, func(i, j int) bool {
return depositCntrs[i].Index < depositCntrs[j].Index
})
depositCntrs := dc.PendingContainers(ctx, untilBlk)
var deposits []*ethpb.Deposit
for _, dep := range depositCntrs {
deposits = append(deposits, dep.Deposit)
}
span.AddAttributes(trace.Int64Attribute("count", int64(len(deposits))))
return deposits
}
// PendingContainers returns a list of deposit containers until the given block number
// (inclusive).
func (dc *DepositCache) PendingContainers(ctx context.Context, beforeBlk *big.Int) []*dbpb.DepositContainer {
func (dc *DepositCache) PendingContainers(ctx context.Context, untilBlk *big.Int) []*dbpb.DepositContainer {
ctx, span := trace.StartSpan(ctx, "DepositsCache.PendingDeposits")
defer span.End()
dc.depositsLock.RLock()
@@ -87,7 +74,7 @@ func (dc *DepositCache) PendingContainers(ctx context.Context, beforeBlk *big.In
var depositCntrs []*dbpb.DepositContainer
for _, ctnr := range dc.pendingDeposits {
if beforeBlk == nil || beforeBlk.Uint64() >= ctnr.Eth1BlockHeight {
if untilBlk == nil || untilBlk.Uint64() >= ctnr.Eth1BlockHeight {
depositCntrs = append(depositCntrs, ctnr)
}
}
@@ -141,7 +128,7 @@ func (dc *DepositCache) RemovePendingDeposit(ctx context.Context, d *ethpb.Depos
}
// PrunePendingDeposits removes any deposit which is older than the given deposit merkle tree index.
func (dc *DepositCache) PrunePendingDeposits(ctx context.Context, merkleTreeIndex int) {
func (dc *DepositCache) PrunePendingDeposits(ctx context.Context, merkleTreeIndex int64) {
ctx, span := trace.StartSpan(ctx, "DepositsCache.PrunePendingDeposits")
defer span.End()
@@ -155,7 +142,7 @@ func (dc *DepositCache) PrunePendingDeposits(ctx context.Context, merkleTreeInde
var cleanDeposits []*dbpb.DepositContainer
for _, dp := range dc.pendingDeposits {
if dp.Index >= int64(merkleTreeIndex) {
if dp.Index >= merkleTreeIndex {
cleanDeposits = append(cleanDeposits, dp)
}
}

View File

@@ -3,13 +3,14 @@ package depositcache
import (
"context"
"math/big"
"reflect"
"testing"
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
dbpb "github.com/prysmaticlabs/prysm/proto/beacon/db"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
)
var _ = PendingDepositsFetcher(&DepositCache{})
@@ -18,25 +19,21 @@ func TestInsertPendingDeposit_OK(t *testing.T) {
dc := DepositCache{}
dc.InsertPendingDeposit(context.Background(), &ethpb.Deposit{}, 111, 100, [32]byte{})
if len(dc.pendingDeposits) != 1 {
t.Error("Deposit not inserted")
}
assert.Equal(t, 1, len(dc.pendingDeposits), "Deposit not inserted")
}
func TestInsertPendingDeposit_ignoresNilDeposit(t *testing.T) {
dc := DepositCache{}
dc.InsertPendingDeposit(context.Background(), nil /*deposit*/, 0 /*blockNum*/, 0, [32]byte{})
if len(dc.pendingDeposits) > 0 {
t.Error("Unexpected deposit insertion")
}
assert.Equal(t, 0, len(dc.pendingDeposits))
}
func TestRemovePendingDeposit_OK(t *testing.T) {
db := DepositCache{}
proof1 := make([][]byte, 33)
proof1 := make([][]byte, int(params.BeaconConfig().DepositContractTreeDepth)+1)
proof1[0] = bytesutil.PadTo([]byte{'A'}, 32)
proof2 := make([][]byte, 33)
proof2 := make([][]byte, int(params.BeaconConfig().DepositContractTreeDepth)+1)
proof2[0] = bytesutil.PadTo([]byte{'A'}, 32)
depToRemove := &ethpb.Deposit{Proof: proof1}
otherDep := &ethpb.Deposit{Proof: proof2}
@@ -55,21 +52,17 @@ func TestRemovePendingDeposit_IgnoresNilDeposit(t *testing.T) {
dc := DepositCache{}
dc.pendingDeposits = []*dbpb.DepositContainer{{Deposit: &ethpb.Deposit{}}}
dc.RemovePendingDeposit(context.Background(), nil /*deposit*/)
if len(dc.pendingDeposits) != 1 {
t.Errorf("Deposit unexpectedly removed")
}
assert.Equal(t, 1, len(dc.pendingDeposits), "Deposit unexpectedly removed")
}
func TestPendingDeposit_RoundTrip(t *testing.T) {
dc := DepositCache{}
proof := make([][]byte, 33)
proof := make([][]byte, int(params.BeaconConfig().DepositContractTreeDepth)+1)
proof[0] = bytesutil.PadTo([]byte{'A'}, 32)
dep := &ethpb.Deposit{Proof: proof}
dc.InsertPendingDeposit(context.Background(), dep, 111, 100, [32]byte{})
dc.RemovePendingDeposit(context.Background(), dep)
if len(dc.pendingDeposits) != 0 {
t.Error("Failed to insert & delete a pending deposit")
}
assert.Equal(t, 0, len(dc.pendingDeposits), "Failed to insert & delete a pending deposit")
}
func TestPendingDeposits_OK(t *testing.T) {
@@ -86,15 +79,10 @@ func TestPendingDeposits_OK(t *testing.T) {
{Proof: [][]byte{[]byte("A")}},
{Proof: [][]byte{[]byte("B")}},
}
if !reflect.DeepEqual(deposits, expected) {
t.Errorf("Unexpected deposits. got=%+v want=%+v", deposits, expected)
}
assert.DeepEqual(t, expected, deposits)
all := dc.PendingDeposits(context.Background(), nil)
if len(all) != len(dc.pendingDeposits) {
t.Error("PendingDeposits(ctx, nil) did not return all deposits")
}
assert.Equal(t, len(dc.pendingDeposits), len(all), "PendingDeposits(ctx, nil) did not return all deposits")
}
func TestPrunePendingDeposits_ZeroMerkleIndex(t *testing.T) {
@@ -118,9 +106,7 @@ func TestPrunePendingDeposits_ZeroMerkleIndex(t *testing.T) {
{Eth1BlockHeight: 10, Index: 10},
{Eth1BlockHeight: 12, Index: 12},
}
if !reflect.DeepEqual(dc.pendingDeposits, expected) {
t.Errorf("Unexpected deposits. got=%+v want=%+v", dc.pendingDeposits, expected)
}
assert.DeepEqual(t, expected, dc.pendingDeposits)
}
func TestPrunePendingDeposits_OK(t *testing.T) {
@@ -143,9 +129,7 @@ func TestPrunePendingDeposits_OK(t *testing.T) {
{Eth1BlockHeight: 12, Index: 12},
}
if !reflect.DeepEqual(dc.pendingDeposits, expected) {
t.Errorf("Unexpected deposits. got=%+v want=%+v", dc.pendingDeposits, expected)
}
assert.DeepEqual(t, expected, dc.pendingDeposits)
dc.pendingDeposits = []*dbpb.DepositContainer{
{Eth1BlockHeight: 2, Index: 2},
@@ -162,8 +146,5 @@ func TestPrunePendingDeposits_OK(t *testing.T) {
{Eth1BlockHeight: 12, Index: 12},
}
if !reflect.DeepEqual(dc.pendingDeposits, expected) {
t.Errorf("Unexpected deposits. got=%+v want=%+v", dc.pendingDeposits, expected)
}
assert.DeepEqual(t, expected, dc.pendingDeposits)
}

5
beacon-chain/cache/doc.go vendored Normal file
View File

@@ -0,0 +1,5 @@
// Package cache includes all important caches for the runtime
// of an eth2 beacon node, ensuring the node does not spend
// resources computing duplicate operations such as committee
// calculations for validators during the same epoch, etc.
package cache

View File

@@ -1,139 +0,0 @@
package cache
import (
"errors"
"sync"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"k8s.io/client-go/tools/cache"
)
var (
// ErrNotEth1DataVote will be returned when a cache object is not a pointer to
// a Eth1DataVote struct.
ErrNotEth1DataVote = errors.New("object is not a eth1 data vote obj")
// maxEth1DataVoteSize defines the max number of eth1 data votes can cache.
maxEth1DataVoteSize = 1000
// Metrics.
eth1DataVoteCacheMiss = promauto.NewCounter(prometheus.CounterOpts{
Name: "eth1_data_vote_cache_miss",
Help: "The number of eth1 data vote count requests that aren't present in the cache.",
})
eth1DataVoteCacheHit = promauto.NewCounter(prometheus.CounterOpts{
Name: "eth1_data_vote_cache_hit",
Help: "The number of eth1 data vote count requests that are present in the cache.",
})
)
// Eth1DataVote defines the struct which keeps track of the vote count of individual deposit root.
type Eth1DataVote struct {
Eth1DataHash [32]byte
VoteCount uint64
}
// Eth1DataVoteCache is a struct with 1 queue for looking up eth1 data vote count by deposit root.
type Eth1DataVoteCache struct {
eth1DataVoteCache *cache.FIFO
lock sync.RWMutex
}
// eth1DataVoteKeyFn takes the eth1data hash as the key for the eth1 data vote count of a given eth1data object.
func eth1DataVoteKeyFn(obj interface{}) (string, error) {
eInfo, ok := obj.(*Eth1DataVote)
if !ok {
return "", ErrNotEth1DataVote
}
return string(eInfo.Eth1DataHash[:]), nil
}
// NewEth1DataVoteCache creates a new eth1 data vote count cache for storing/accessing Eth1DataVote.
func NewEth1DataVoteCache() *Eth1DataVoteCache {
return &Eth1DataVoteCache{
eth1DataVoteCache: cache.NewFIFO(eth1DataVoteKeyFn),
}
}
// Eth1DataVote fetches eth1 data vote count by the eth1data hash. Returns vote count,
// if exists. Otherwise returns false, nil.
func (c *Eth1DataVoteCache) Eth1DataVote(eth1DataHash [32]byte) (uint64, error) {
if !featureconfig.Get().EnableEth1DataVoteCache {
// Return a miss result if cache is not enabled.
eth1DataVoteCacheMiss.Inc()
return 0, nil
}
c.lock.RLock()
defer c.lock.RUnlock()
obj, exists, err := c.eth1DataVoteCache.GetByKey(string(eth1DataHash[:]))
if err != nil {
return 0, err
}
if exists {
eth1DataVoteCacheHit.Inc()
} else {
eth1DataVoteCacheMiss.Inc()
return 0, nil
}
eInfo, ok := obj.(*Eth1DataVote)
if !ok {
return 0, ErrNotEth1DataVote
}
return eInfo.VoteCount, nil
}
// AddEth1DataVote adds eth1 data vote object to the cache. This method also trims the least
// recently added Eth1DataVoteByEpoch object if the cache size has ready the max cache size limit.
func (c *Eth1DataVoteCache) AddEth1DataVote(eth1DataVote *Eth1DataVote) error {
if !featureconfig.Get().EnableEth1DataVoteCache {
return nil
}
c.lock.Lock()
defer c.lock.Unlock()
if err := c.eth1DataVoteCache.Add(eth1DataVote); err != nil {
return err
}
trim(c.eth1DataVoteCache, maxEth1DataVoteSize)
return nil
}
// IncrementEth1DataVote increments the existing eth1 data object's vote count by 1,
// and returns the vote count.
func (c *Eth1DataVoteCache) IncrementEth1DataVote(eth1DataHash [32]byte) (uint64, error) {
if !featureconfig.Get().EnableEth1DataVoteCache {
return 0, nil
}
c.lock.RLock()
defer c.lock.RUnlock()
obj, exists, err := c.eth1DataVoteCache.GetByKey(string(eth1DataHash[:]))
if err != nil {
return 0, err
}
if !exists {
return 0, errors.New("eth1 data vote object does not exist")
}
eth1DataVoteCacheHit.Inc()
eInfo, ok := obj.(*Eth1DataVote)
if !ok {
return 0, errors.New("cached value is not of type *Eth1DataVote")
}
eInfo.VoteCount++
if err := c.eth1DataVoteCache.Add(eInfo); err != nil {
return 0, err
}
return eInfo.VoteCount, nil
}

View File

@@ -1,113 +0,0 @@
package cache
import (
"strconv"
"testing"
)
func TestEth1DataVoteKeyFn_OK(t *testing.T) {
eInfo := &Eth1DataVote{
VoteCount: 44,
Eth1DataHash: [32]byte{'A'},
}
key, err := eth1DataVoteKeyFn(eInfo)
if err != nil {
t.Fatal(err)
}
if key != string(eInfo.Eth1DataHash[:]) {
t.Errorf("Incorrect hash key: %s, expected %s", key, string(eInfo.Eth1DataHash[:]))
}
}
func TestEth1DataVoteKeyFn_InvalidObj(t *testing.T) {
_, err := eth1DataVoteKeyFn("bad")
if err != ErrNotEth1DataVote {
t.Errorf("Expected error %v, got %v", ErrNotEth1DataVote, err)
}
}
func TestEth1DataVoteCache_CanAdd(t *testing.T) {
cache := NewEth1DataVoteCache()
eInfo := &Eth1DataVote{
VoteCount: 55,
Eth1DataHash: [32]byte{'B'},
}
count, err := cache.Eth1DataVote(eInfo.Eth1DataHash)
if err != nil {
t.Fatal(err)
}
if count != 0 {
t.Error("Expected seed not to exist in empty cache")
}
if err := cache.AddEth1DataVote(eInfo); err != nil {
t.Fatal(err)
}
count, err = cache.Eth1DataVote(eInfo.Eth1DataHash)
if err != nil {
t.Fatal(err)
}
if count != eInfo.VoteCount {
t.Errorf(
"Expected vote count to be %d, got %d",
eInfo.VoteCount,
count,
)
}
}
func TestEth1DataVoteCache_CanIncrement(t *testing.T) {
cache := NewEth1DataVoteCache()
eInfo := &Eth1DataVote{
VoteCount: 55,
Eth1DataHash: [32]byte{'B'},
}
if err := cache.AddEth1DataVote(eInfo); err != nil {
t.Fatal(err)
}
_, err := cache.IncrementEth1DataVote(eInfo.Eth1DataHash)
if err != nil {
t.Fatal(err)
}
_, err = cache.IncrementEth1DataVote(eInfo.Eth1DataHash)
if err != nil {
t.Error(err)
}
count, err := cache.IncrementEth1DataVote(eInfo.Eth1DataHash)
if count != 58 {
t.Errorf(
"Expected vote count to be %d, got %d",
58,
count,
)
}
}
func TestEth1Data_MaxSize(t *testing.T) {
cache := NewEth1DataVoteCache()
for i := 0; i < maxEth1DataVoteSize+1; i++ {
var hash [32]byte
copy(hash[:], strconv.Itoa(i))
eInfo := &Eth1DataVote{
Eth1DataHash: hash,
}
if err := cache.AddEth1DataVote(eInfo); err != nil {
t.Fatal(err)
}
}
if len(cache.eth1DataVoteCache.ListKeys()) != maxEth1DataVoteSize {
t.Errorf(
"Expected hash cache key size to be %d, got %d",
maxEth1DataVoteSize,
len(cache.eth1DataVoteCache.ListKeys()),
)
}
}

View File

@@ -1,9 +1,14 @@
package cache
import "github.com/prysmaticlabs/prysm/shared/featureconfig"
import (
"os"
"testing"
func init() {
featureconfig.Init(&featureconfig.Flags{
EnableEth1DataVoteCache: true,
})
"github.com/prysmaticlabs/prysm/shared/featureconfig"
)
func TestMain(m *testing.M) {
resetCfg := featureconfig.InitWithReset(&featureconfig.Flags{EnableEth1DataVoteCache: true})
defer resetCfg()
os.Exit(m.Run())
}

View File

@@ -1,6 +1,8 @@
package cache
import (
"sync"
lru "github.com/hashicorp/golang-lru"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
@@ -9,7 +11,7 @@ import (
var (
// hotStateCacheSize defines the max number of hot state this can cache.
hotStateCacheSize = 16
hotStateCacheSize = 32
// Metrics
hotStateCacheHit = promauto.NewCounter(prometheus.CounterOpts{
Name: "hot_state_cache_hit",
@@ -24,6 +26,7 @@ var (
// HotStateCache is used to store the processed beacon state after finalized check point..
type HotStateCache struct {
cache *lru.Cache
lock sync.RWMutex
}
// NewHotStateCache initializes the map and underlying cache.
@@ -40,6 +43,8 @@ func NewHotStateCache() *HotStateCache {
// Get returns a cached response via input block root, if any.
// The response is copied by default.
func (c *HotStateCache) Get(root [32]byte) *stateTrie.BeaconState {
c.lock.RLock()
defer c.lock.RUnlock()
item, exists := c.cache.Get(root)
if exists && item != nil {
@@ -50,12 +55,36 @@ func (c *HotStateCache) Get(root [32]byte) *stateTrie.BeaconState {
return nil
}
// GetWithoutCopy returns a non-copied cached response via input block root.
func (c *HotStateCache) GetWithoutCopy(root [32]byte) *stateTrie.BeaconState {
c.lock.RLock()
defer c.lock.RUnlock()
item, exists := c.cache.Get(root)
if exists && item != nil {
hotStateCacheHit.Inc()
return item.(*stateTrie.BeaconState)
}
hotStateCacheMiss.Inc()
return nil
}
// Put the response in the cache.
func (c *HotStateCache) Put(root [32]byte, state *stateTrie.BeaconState) {
c.lock.Lock()
defer c.lock.Unlock()
c.cache.Add(root, state)
}
// Has returns true if the key exists in the cache.
func (c *HotStateCache) Has(root [32]byte) bool {
c.lock.RLock()
defer c.lock.RUnlock()
return c.cache.Contains(root)
}
// Delete deletes the key exists in the cache.
func (c *HotStateCache) Delete(root [32]byte) bool {
c.lock.Lock()
defer c.lock.Unlock()
return c.cache.Remove(root)
}

View File

@@ -1,41 +1,34 @@
package cache_test
import (
"reflect"
"testing"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestHotStateCache_RoundTrip(t *testing.T) {
c := cache.NewHotStateCache()
root := [32]byte{'A'}
state := c.Get(root)
if state != nil {
t.Errorf("Empty cache returned an object: %v", state)
}
if c.Has(root) {
t.Error("Empty cache has an object")
}
assert.Equal(t, (*stateTrie.BeaconState)(nil), state)
assert.Equal(t, false, c.Has(root), "Empty cache has an object")
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 10,
})
if err != nil {
t.Fatal(err)
}
c.Put(root, state)
require.NoError(t, err)
c.Put(root, state)
assert.Equal(t, true, c.Has(root), "Empty cache does not have an object")
if !c.Has(root) {
t.Error("Empty cache does not have an object")
}
res := c.Get(root)
if state == nil {
t.Errorf("Empty cache returned an object: %v", state)
}
if !reflect.DeepEqual(state.CloneInnerState(), res.CloneInnerState()) {
t.Error("Expected equal protos to return from cache")
}
assert.NotNil(t, state)
assert.DeepEqual(t, res.CloneInnerState(), state.CloneInnerState(), "Expected equal protos to return from cache")
c.Delete(root)
assert.Equal(t, false, c.Has(root), "Cache not supposed to have the object")
}

View File

@@ -2,12 +2,13 @@ package cache_test
import (
"context"
"reflect"
"testing"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestSkipSlotCache_RoundTrip(t *testing.T) {
@@ -15,39 +16,20 @@ func TestSkipSlotCache_RoundTrip(t *testing.T) {
c := cache.NewSkipSlotCache()
state, err := c.Get(ctx, 5)
if err != nil {
t.Error(err)
}
require.NoError(t, err)
assert.Equal(t, (*stateTrie.BeaconState)(nil), state, "Empty cache returned an object")
if state != nil {
t.Errorf("Empty cache returned an object: %v", state)
}
if err := c.MarkInProgress(5); err != nil {
t.Error(err)
}
require.NoError(t, c.MarkInProgress(5))
state, err = stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 10,
})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if err = c.Put(ctx, 5, state); err != nil {
t.Error(err)
}
if err := c.MarkNotInProgress(5); err != nil {
t.Error(err)
}
require.NoError(t, c.Put(ctx, 5, state))
require.NoError(t, c.MarkNotInProgress(5))
res, err := c.Get(ctx, 5)
if err != nil {
t.Error(err)
}
if !reflect.DeepEqual(state.CloneInnerState(), res.CloneInnerState()) {
t.Error("Expected equal protos to return from cache")
}
require.NoError(t, err)
assert.DeepEqual(t, res.CloneInnerState(), state.CloneInnerState(), "Expected equal protos to return from cache")
}

134
beacon-chain/cache/subnet_ids.go vendored Normal file
View File

@@ -0,0 +1,134 @@
package cache
import (
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/patrickmn/go-cache"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/sliceutil"
)
type subnetIDs struct {
attester *lru.Cache
attesterLock sync.RWMutex
aggregator *lru.Cache
aggregatorLock sync.RWMutex
persistentSubnets *cache.Cache
subnetsLock sync.RWMutex
}
// SubnetIDs for attester and aggregator.
var SubnetIDs = newSubnetIDs()
func newSubnetIDs() *subnetIDs {
// Given a node can calculate committee assignments of current epoch and next epoch.
// Max size is set to 2 epoch length.
cacheSize := params.BeaconConfig().MaxCommitteesPerSlot * params.BeaconConfig().SlotsPerEpoch * 2
attesterCache, err := lru.New(int(cacheSize))
if err != nil {
panic(err)
}
aggregatorCache, err := lru.New(int(cacheSize))
if err != nil {
panic(err)
}
epochDuration := time.Duration(params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().SecondsPerSlot)
subLength := epochDuration * time.Duration(params.BeaconNetworkConfig().EpochsPerRandomSubnetSubscription)
persistentCache := cache.New(subLength*time.Second, epochDuration*time.Second)
return &subnetIDs{attester: attesterCache, aggregator: aggregatorCache, persistentSubnets: persistentCache}
}
// AddAttesterSubnetID adds the subnet index for subscribing subnet for the attester of a given slot.
func (c *subnetIDs) AddAttesterSubnetID(slot uint64, subnetID uint64) {
c.attesterLock.Lock()
defer c.attesterLock.Unlock()
ids := []uint64{subnetID}
val, exists := c.attester.Get(slot)
if exists {
ids = sliceutil.UnionUint64(append(val.([]uint64), ids...))
}
c.attester.Add(slot, ids)
}
// GetAttesterSubnetIDs gets the subnet IDs for subscribed subnets for attesters of the slot.
func (c *subnetIDs) GetAttesterSubnetIDs(slot uint64) []uint64 {
c.attesterLock.RLock()
defer c.attesterLock.RUnlock()
val, exists := c.attester.Get(slot)
if !exists {
return nil
}
if v, ok := val.([]uint64); ok {
return v
}
return nil
}
// AddAggregatorSubnetID adds the subnet ID for subscribing subnet for the aggregator of a given slot.
func (c *subnetIDs) AddAggregatorSubnetID(slot uint64, subnetID uint64) {
c.aggregatorLock.Lock()
defer c.aggregatorLock.Unlock()
ids := []uint64{subnetID}
val, exists := c.aggregator.Get(slot)
if exists {
ids = sliceutil.UnionUint64(append(val.([]uint64), ids...))
}
c.aggregator.Add(slot, ids)
}
// GetAggregatorSubnetIDs gets the subnet IDs for subscribing subnet for aggregator of the slot.
func (c *subnetIDs) GetAggregatorSubnetIDs(slot uint64) []uint64 {
c.aggregatorLock.RLock()
defer c.aggregatorLock.RUnlock()
val, exists := c.aggregator.Get(slot)
if !exists {
return []uint64{}
}
return val.([]uint64)
}
// GetPersistentSubnets retrieves the persistent subnet and expiration time of that validator's
// subscription.
func (c *subnetIDs) GetPersistentSubnets(pubkey []byte) ([]uint64, bool, time.Time) {
c.subnetsLock.RLock()
defer c.subnetsLock.RUnlock()
id, duration, ok := c.persistentSubnets.GetWithExpiration(string(pubkey))
if !ok {
return []uint64{}, ok, time.Time{}
}
return id.([]uint64), ok, duration
}
// GetAllSubnets retrieves all the non-expired subscribed subnets of all the validators
// in the cache.
func (c *subnetIDs) GetAllSubnets() []uint64 {
c.subnetsLock.RLock()
defer c.subnetsLock.RUnlock()
itemsMap := c.persistentSubnets.Items()
committees := []uint64{}
for _, v := range itemsMap {
if v.Expired() {
continue
}
committees = append(committees, v.Object.([]uint64)...)
}
return sliceutil.SetUint64(committees)
}
// AddPersistentCommittee adds the relevant committee for that particular validator along with its
// expiration period.
func (c *subnetIDs) AddPersistentCommittee(pubkey []byte, comIndex []uint64, duration time.Duration) {
c.subnetsLock.Lock()
defer c.subnetsLock.Unlock()
c.persistentSubnets.Set(string(pubkey), comIndex, duration)
}

66
beacon-chain/cache/subnet_ids_test.go vendored Normal file
View File

@@ -0,0 +1,66 @@
package cache
import (
"testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestSubnetIDsCache_RoundTrip(t *testing.T) {
c := newSubnetIDs()
slot := uint64(100)
committeeIDs := c.GetAggregatorSubnetIDs(slot)
assert.Equal(t, 0, len(committeeIDs), "Empty cache returned an object")
c.AddAggregatorSubnetID(slot, 1)
res := c.GetAggregatorSubnetIDs(slot)
assert.DeepEqual(t, []uint64{1}, res)
c.AddAggregatorSubnetID(slot, 2)
res = c.GetAggregatorSubnetIDs(slot)
assert.DeepEqual(t, []uint64{1, 2}, res)
c.AddAggregatorSubnetID(slot, 3)
res = c.GetAggregatorSubnetIDs(slot)
assert.DeepEqual(t, []uint64{1, 2, 3}, res)
committeeIDs = c.GetAttesterSubnetIDs(slot)
assert.Equal(t, 0, len(committeeIDs), "Empty cache returned an object")
c.AddAttesterSubnetID(slot, 11)
res = c.GetAttesterSubnetIDs(slot)
assert.DeepEqual(t, []uint64{11}, res)
c.AddAttesterSubnetID(slot, 22)
res = c.GetAttesterSubnetIDs(slot)
assert.DeepEqual(t, []uint64{11, 22}, res)
c.AddAttesterSubnetID(slot, 33)
res = c.GetAttesterSubnetIDs(slot)
assert.DeepEqual(t, []uint64{11, 22, 33}, res)
}
func TestSubnetIDsCache_PersistentCommitteeRoundtrip(t *testing.T) {
pubkeySet := [][48]byte{}
c := newSubnetIDs()
for i := 0; i < 20; i++ {
pubkey := [48]byte{byte(i)}
pubkeySet = append(pubkeySet, pubkey)
c.AddPersistentCommittee(pubkey[:], []uint64{uint64(i)}, 0)
}
for i := uint64(0); i < 20; i++ {
pubkey := [48]byte{byte(i)}
idxs, ok, _ := c.GetPersistentSubnets(pubkey[:])
if !ok {
t.Errorf("Couldn't find entry in cache for pubkey %#x", pubkey)
continue
}
require.Equal(t, i, idxs[0])
}
coms := c.GetAllSubnets()
assert.Equal(t, 20, len(coms))
}

View File

@@ -1,18 +1,28 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
load("@prysm//tools/go:def.bzl", "go_library")
load("@io_bazel_rules_go//go:def.bzl", "go_test")
go_library(
name = "go_default_library",
srcs = [
"block.go",
"block_operations.go",
"attestation.go",
"attester_slashing.go",
"deposit.go",
"eth1_data.go",
"exit.go",
"genesis.go",
"header.go",
"log.go",
"proposer_slashing.go",
"randao.go",
"signature.go",
],
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks",
visibility = [
"//beacon-chain:__subpackages__",
"//fuzz:__pkg__",
"//shared/testutil:__pkg__",
],
deps = [
"//beacon-chain/cache:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/core/validators:go_default_library",
"//beacon-chain/state:go_default_library",
@@ -21,7 +31,7 @@ go_library(
"//shared/attestationutil:go_default_library",
"//shared/bls:go_default_library",
"//shared/bytesutil:go_default_library",
"//shared/featureconfig:go_default_library",
"//shared/depositutil:go_default_library",
"//shared/hashutil:go_default_library",
"//shared/mathutil:go_default_library",
"//shared/params:go_default_library",
@@ -40,11 +50,17 @@ go_test(
name = "go_default_test",
size = "medium",
srcs = [
"attestation_test.go",
"attester_slashing_test.go",
"block_operations_fuzz_test.go",
"block_operations_test.go",
"block_regression_test.go",
"block_test.go",
"deposit_test.go",
"eth1_data_test.go",
"exit_test.go",
"genesis_test.go",
"header_test.go",
"proposer_slashing_test.go",
"randao_test.go",
],
embed = [":go_default_library"],
deps = [
@@ -52,11 +68,14 @@ go_test(
"//beacon-chain/state:go_default_library",
"//beacon-chain/state/stateutil:go_default_library",
"//proto/beacon/p2p/v1:go_default_library",
"//shared/aggregation:go_default_library",
"//shared/aggregation/attestations:go_default_library",
"//shared/attestationutil:go_default_library",
"//shared/bls:go_default_library",
"//shared/bytesutil:go_default_library",
"//shared/params:go_default_library",
"//shared/testutil:go_default_library",
"//shared/testutil/require:go_default_library",
"//shared/trieutil:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_google_gofuzz//:go_default_library",
@@ -64,6 +83,5 @@ go_test(
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
"@com_github_prysmaticlabs_go_ssz//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@in_gopkg_d4l3k_messagediff_v1//:go_default_library",
],
)

View File

@@ -0,0 +1,327 @@
package blocks
import (
"bytes"
"context"
"fmt"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/attestationutil"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/params"
"go.opencensus.io/trace"
)
// ProcessAttestations applies processing operations to a block's inner attestation
// records.
func ProcessAttestations(
ctx context.Context,
beaconState *stateTrie.BeaconState,
body *ethpb.BeaconBlockBody,
) (*stateTrie.BeaconState, error) {
var err error
for idx, attestation := range body.Attestations {
beaconState, err = ProcessAttestation(ctx, beaconState, attestation)
if err != nil {
return nil, errors.Wrapf(err, "could not verify attestation at index %d in block", idx)
}
}
return beaconState, nil
}
// ProcessAttestation verifies an input attestation can pass through processing using the given beacon state.
//
// Spec pseudocode definition:
// def process_attestation(state: BeaconState, attestation: Attestation) -> None:
// data = attestation.data
// assert data.target.epoch in (get_previous_epoch(state), get_current_epoch(state))
// assert data.target.epoch == compute_epoch_at_slot(data.slot)
// assert data.slot + MIN_ATTESTATION_INCLUSION_DELAY <= state.slot <= data.slot + SLOTS_PER_EPOCH
// assert data.index < get_committee_count_per_slot(state, data.target.epoch)
//
// committee = get_beacon_committee(state, data.slot, data.index)
// assert len(attestation.aggregation_bits) == len(committee)
//
// pending_attestation = PendingAttestation(
// data=data,
// aggregation_bits=attestation.aggregation_bits,
// inclusion_delay=state.slot - data.slot,
// proposer_index=get_beacon_proposer_index(state),
// )
//
// if data.target.epoch == get_current_epoch(state):
// assert data.source == state.current_justified_checkpoint
// state.current_epoch_attestations.append(pending_attestation)
// else:
// assert data.source == state.previous_justified_checkpoint
// state.previous_epoch_attestations.append(pending_attestation)
//
// # Check signature
// assert is_valid_indexed_attestation(state, get_indexed_attestation(state, attestation))
func ProcessAttestation(
ctx context.Context,
beaconState *stateTrie.BeaconState,
att *ethpb.Attestation,
) (*stateTrie.BeaconState, error) {
beaconState, err := ProcessAttestationNoVerify(ctx, beaconState, att)
if err != nil {
return nil, err
}
return beaconState, VerifyAttestation(ctx, beaconState, att)
}
// ProcessAttestationsNoVerify applies processing operations to a block's inner attestation
// records. The only difference would be that the attestation signature would not be verified.
func ProcessAttestationsNoVerify(
ctx context.Context,
beaconState *stateTrie.BeaconState,
body *ethpb.BeaconBlockBody,
) (*stateTrie.BeaconState, error) {
var err error
for idx, attestation := range body.Attestations {
beaconState, err = ProcessAttestationNoVerify(ctx, beaconState, attestation)
if err != nil {
return nil, errors.Wrapf(err, "could not verify attestation at index %d in block", idx)
}
}
return beaconState, nil
}
// ProcessAttestationNoVerify processes the attestation without verifying the attestation signature. This
// method is used to validate attestations whose signatures have already been verified.
func ProcessAttestationNoVerify(
ctx context.Context,
beaconState *stateTrie.BeaconState,
att *ethpb.Attestation,
) (*stateTrie.BeaconState, error) {
ctx, span := trace.StartSpan(ctx, "core.ProcessAttestationNoVerify")
defer span.End()
if att == nil || att.Data == nil || att.Data.Target == nil {
return nil, errors.New("nil attestation data target")
}
currEpoch := helpers.SlotToEpoch(beaconState.Slot())
var prevEpoch uint64
if currEpoch == 0 {
prevEpoch = 0
} else {
prevEpoch = currEpoch - 1
}
data := att.Data
if data.Target.Epoch != prevEpoch && data.Target.Epoch != currEpoch {
return nil, fmt.Errorf(
"expected target epoch (%d) to be the previous epoch (%d) or the current epoch (%d)",
data.Target.Epoch,
prevEpoch,
currEpoch,
)
}
if helpers.SlotToEpoch(data.Slot) != data.Target.Epoch {
return nil, fmt.Errorf("data slot is not in the same epoch as target %d != %d", helpers.SlotToEpoch(data.Slot), data.Target.Epoch)
}
s := att.Data.Slot
minInclusionCheck := s+params.BeaconConfig().MinAttestationInclusionDelay <= beaconState.Slot()
epochInclusionCheck := beaconState.Slot() <= s+params.BeaconConfig().SlotsPerEpoch
if !minInclusionCheck {
return nil, fmt.Errorf(
"attestation slot %d + inclusion delay %d > state slot %d",
s,
params.BeaconConfig().MinAttestationInclusionDelay,
beaconState.Slot(),
)
}
if !epochInclusionCheck {
return nil, fmt.Errorf(
"state slot %d > attestation slot %d + SLOTS_PER_EPOCH %d",
beaconState.Slot(),
s,
params.BeaconConfig().SlotsPerEpoch,
)
}
activeValidatorCount, err := helpers.ActiveValidatorCount(beaconState, att.Data.Target.Epoch)
if err != nil {
return nil, err
}
c := helpers.SlotCommitteeCount(activeValidatorCount)
if att.Data.CommitteeIndex > c {
return nil, fmt.Errorf("committee index %d >= committee count %d", att.Data.CommitteeIndex, c)
}
if err := helpers.VerifyAttestationBitfieldLengths(beaconState, att); err != nil {
return nil, errors.Wrap(err, "could not verify attestation bitfields")
}
proposerIndex, err := helpers.BeaconProposerIndex(beaconState)
if err != nil {
return nil, err
}
pendingAtt := &pb.PendingAttestation{
Data: data,
AggregationBits: att.AggregationBits,
InclusionDelay: beaconState.Slot() - s,
ProposerIndex: proposerIndex,
}
var ffgSourceEpoch uint64
var ffgSourceRoot []byte
var ffgTargetEpoch uint64
if data.Target.Epoch == currEpoch {
ffgSourceEpoch = beaconState.CurrentJustifiedCheckpoint().Epoch
ffgSourceRoot = beaconState.CurrentJustifiedCheckpoint().Root
ffgTargetEpoch = currEpoch
if err := beaconState.AppendCurrentEpochAttestations(pendingAtt); err != nil {
return nil, err
}
} else {
ffgSourceEpoch = beaconState.PreviousJustifiedCheckpoint().Epoch
ffgSourceRoot = beaconState.PreviousJustifiedCheckpoint().Root
ffgTargetEpoch = prevEpoch
if err := beaconState.AppendPreviousEpochAttestations(pendingAtt); err != nil {
return nil, err
}
}
if data.Source.Epoch != ffgSourceEpoch {
return nil, fmt.Errorf("expected source epoch %d, received %d", ffgSourceEpoch, data.Source.Epoch)
}
if !bytes.Equal(data.Source.Root, ffgSourceRoot) {
return nil, fmt.Errorf("expected source root %#x, received %#x", ffgSourceRoot, data.Source.Root)
}
if data.Target.Epoch != ffgTargetEpoch {
return nil, fmt.Errorf("expected target epoch %d, received %d", ffgTargetEpoch, data.Target.Epoch)
}
return beaconState, nil
}
// VerifyIndexedAttestation determines the validity of an indexed attestation.
//
// Spec pseudocode definition:
// def is_valid_indexed_attestation(state: BeaconState, indexed_attestation: IndexedAttestation) -> bool:
// """
// Check if ``indexed_attestation`` is not empty, has sorted and unique indices and has a valid aggregate signature.
// """
// # Verify indices are sorted and unique
// indices = indexed_attestation.attesting_indices
// if len(indices) == 0 or not indices == sorted(set(indices)):
// return False
// # Verify aggregate signature
// pubkeys = [state.validators[i].pubkey for i in indices]
// domain = get_domain(state, DOMAIN_BEACON_ATTESTER, indexed_attestation.data.target.epoch)
// signing_root = compute_signing_root(indexed_attestation.data, domain)
// return bls.FastAggregateVerify(pubkeys, signing_root, indexed_attestation.signature)
func VerifyIndexedAttestation(ctx context.Context, beaconState *stateTrie.BeaconState, indexedAtt *ethpb.IndexedAttestation) error {
ctx, span := trace.StartSpan(ctx, "core.VerifyIndexedAttestation")
defer span.End()
if err := attestationutil.IsValidAttestationIndices(ctx, indexedAtt); err != nil {
return err
}
domain, err := helpers.Domain(beaconState.Fork(), indexedAtt.Data.Target.Epoch, params.BeaconConfig().DomainBeaconAttester, beaconState.GenesisValidatorRoot())
if err != nil {
return err
}
indices := indexedAtt.AttestingIndices
pubkeys := []bls.PublicKey{}
for i := 0; i < len(indices); i++ {
pubkeyAtIdx := beaconState.PubkeyAtIndex(indices[i])
pk, err := bls.PublicKeyFromBytes(pubkeyAtIdx[:])
if err != nil {
return errors.Wrap(err, "could not deserialize validator public key")
}
pubkeys = append(pubkeys, pk)
}
return attestationutil.VerifyIndexedAttestationSig(ctx, indexedAtt, pubkeys, domain)
}
// VerifyAttestation converts and attestation into an indexed attestation and verifies
// the signature in that attestation.
func VerifyAttestation(ctx context.Context, beaconState *stateTrie.BeaconState, att *ethpb.Attestation) error {
if att == nil || att.Data == nil {
return fmt.Errorf("nil or missing attestation data: %v", att)
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return err
}
indexedAtt := attestationutil.ConvertToIndexed(ctx, att, committee)
return VerifyIndexedAttestation(ctx, beaconState, indexedAtt)
}
// VerifyAttestations will verify the signatures of the provided attestations. This method performs
// a single BLS verification call to verify the signatures of all of the provided attestations. All
// of the provided attestations must have valid signatures or this method will return an error.
// This method does not determine which attestation signature is invalid, only that one or more
// attestation signatures were not valid.
func VerifyAttestations(ctx context.Context, beaconState *stateTrie.BeaconState, atts []*ethpb.Attestation) error {
ctx, span := trace.StartSpan(ctx, "core.VerifyAttestations")
defer span.End()
span.AddAttributes(trace.Int64Attribute("attestations", int64(len(atts))))
if len(atts) == 0 {
return nil
}
fork := beaconState.Fork()
gvr := beaconState.GenesisValidatorRoot()
dt := params.BeaconConfig().DomainBeaconAttester
// Split attestations by fork. Note: the signature domain will differ based on the fork.
var preForkAtts []*ethpb.Attestation
var postForkAtts []*ethpb.Attestation
for _, a := range atts {
if helpers.SlotToEpoch(a.Data.Slot) < fork.Epoch {
preForkAtts = append(preForkAtts, a)
} else {
postForkAtts = append(postForkAtts, a)
}
}
// Check attestations from before the fork.
if fork.Epoch > 0 { // Check to prevent underflow.
prevDomain, err := helpers.Domain(fork, fork.Epoch-1, dt, gvr)
if err != nil {
return err
}
if err := verifyAttestationsWithDomain(ctx, beaconState, preForkAtts, prevDomain); err != nil {
return err
}
} else if len(preForkAtts) > 0 {
// This is a sanity check that preForkAtts were not ignored when fork.Epoch == 0. This
// condition is not possible, but it doesn't hurt to check anyway.
return errors.New("some attestations were not verified from previous fork before genesis")
}
// Then check attestations from after the fork.
currDomain, err := helpers.Domain(fork, fork.Epoch, dt, gvr)
if err != nil {
return err
}
return verifyAttestationsWithDomain(ctx, beaconState, postForkAtts, currDomain)
}
// Inner method to verify attestations. This abstraction allows for the domain to be provided as an
// argument.
func verifyAttestationsWithDomain(ctx context.Context, beaconState *stateTrie.BeaconState, atts []*ethpb.Attestation, domain []byte) error {
if len(atts) == 0 {
return nil
}
set, err := createAttestationSignatureSet(ctx, beaconState, atts, domain)
if err != nil {
return err
}
verify, err := bls.VerifyMultipleSignatures(set.Signatures, set.Messages, set.PublicKeys)
if err != nil {
return errors.Errorf("got error in multiple verification: %v", err)
}
if !verify {
return errors.New("one or more attestation signatures did not verify")
}
return nil
}

View File

@@ -0,0 +1,962 @@
package blocks_test
import (
"context"
"fmt"
"reflect"
"strings"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/aggregation"
attaggregation "github.com/prysmaticlabs/prysm/shared/aggregation/attestations"
"github.com/prysmaticlabs/prysm/shared/attestationutil"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestProcessAttestations_InclusionDelayFailure(t *testing.T) {
attestations := []*ethpb.Attestation{
{
Data: &ethpb.AttestationData{
Target: &ethpb.Checkpoint{Epoch: 0},
Slot: 5,
},
},
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Attestations: attestations,
},
}
beaconState, _ := testutil.DeterministicGenesisState(t, 100)
want := fmt.Sprintf(
"attestation slot %d + inclusion delay %d > state slot %d",
attestations[0].Data.Slot,
params.BeaconConfig().MinAttestationInclusionDelay,
beaconState.Slot(),
)
_, err := blocks.ProcessAttestations(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessAttestations_NeitherCurrentNorPrevEpoch(t *testing.T) {
att := &ethpb.Attestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0, Root: []byte("hello-world")},
Target: &ethpb.Checkpoint{Epoch: 0}}}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Attestations: []*ethpb.Attestation{att},
},
}
beaconState, _ := testutil.DeterministicGenesisState(t, 100)
err := beaconState.SetSlot(beaconState.Slot() + params.BeaconConfig().SlotsPerEpoch*4 + params.BeaconConfig().MinAttestationInclusionDelay)
if err != nil {
t.Fatal(err)
}
pfc := beaconState.PreviousJustifiedCheckpoint()
pfc.Root = []byte("hello-world")
if err := beaconState.SetPreviousJustifiedCheckpoint(pfc); err != nil {
t.Fatal(err)
}
if err := beaconState.SetPreviousEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
want := fmt.Sprintf(
"expected target epoch (%d) to be the previous epoch (%d) or the current epoch (%d)",
att.Data.Target.Epoch,
helpers.PrevEpoch(beaconState),
helpers.CurrentEpoch(beaconState),
)
_, err = blocks.ProcessAttestations(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessAttestations_CurrentEpochFFGDataMismatches(t *testing.T) {
aggBits := bitfield.NewBitlist(3)
attestations := []*ethpb.Attestation{
{
Data: &ethpb.AttestationData{
Target: &ethpb.Checkpoint{Epoch: 0},
Source: &ethpb.Checkpoint{Epoch: 1},
},
AggregationBits: aggBits,
},
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Attestations: attestations,
},
}
beaconState, _ := testutil.DeterministicGenesisState(t, 100)
if err := beaconState.SetSlot(beaconState.Slot() + params.BeaconConfig().MinAttestationInclusionDelay); err != nil {
t.Fatal(err)
}
cfc := beaconState.CurrentJustifiedCheckpoint()
cfc.Root = []byte("hello-world")
if err := beaconState.SetCurrentJustifiedCheckpoint(cfc); err != nil {
t.Fatal(err)
}
if err := beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
want := fmt.Sprintf(
"expected source epoch %d, received %d",
helpers.CurrentEpoch(beaconState),
attestations[0].Data.Source.Epoch,
)
_, err := blocks.ProcessAttestations(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
block.Body.Attestations[0].Data.Source.Epoch = helpers.CurrentEpoch(beaconState)
block.Body.Attestations[0].Data.Source.Root = []byte{}
want = fmt.Sprintf(
"expected source root %#x, received %#x",
beaconState.CurrentJustifiedCheckpoint().Root,
attestations[0].Data.Source.Root,
)
_, err = blocks.ProcessAttestations(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessAttestations_PrevEpochFFGDataMismatches(t *testing.T) {
beaconState, _ := testutil.DeterministicGenesisState(t, 100)
aggBits := bitfield.NewBitlist(3)
aggBits.SetBitAt(0, true)
attestations := []*ethpb.Attestation{
{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 1},
Target: &ethpb.Checkpoint{Epoch: 1},
Slot: params.BeaconConfig().SlotsPerEpoch,
},
AggregationBits: aggBits,
},
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Attestations: attestations,
},
}
err := beaconState.SetSlot(beaconState.Slot() + params.BeaconConfig().SlotsPerEpoch + params.BeaconConfig().MinAttestationInclusionDelay)
if err != nil {
t.Fatal(err)
}
pfc := beaconState.PreviousJustifiedCheckpoint()
pfc.Root = []byte("hello-world")
if err := beaconState.SetPreviousJustifiedCheckpoint(pfc); err != nil {
t.Fatal(err)
}
if err := beaconState.SetPreviousEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
want := fmt.Sprintf(
"expected source epoch %d, received %d",
helpers.PrevEpoch(beaconState),
attestations[0].Data.Source.Epoch,
)
_, err = blocks.ProcessAttestations(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
block.Body.Attestations[0].Data.Source.Epoch = helpers.PrevEpoch(beaconState)
block.Body.Attestations[0].Data.Target.Epoch = helpers.CurrentEpoch(beaconState)
block.Body.Attestations[0].Data.Source.Root = []byte{}
want = fmt.Sprintf(
"expected source root %#x, received %#x",
beaconState.CurrentJustifiedCheckpoint().Root,
attestations[0].Data.Source.Root,
)
_, err = blocks.ProcessAttestations(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessAttestations_InvalidAggregationBitsLength(t *testing.T) {
beaconState, _ := testutil.DeterministicGenesisState(t, 100)
aggBits := bitfield.NewBitlist(4)
att := &ethpb.Attestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0, Root: []byte("hello-world")},
Target: &ethpb.Checkpoint{Epoch: 0}},
AggregationBits: aggBits,
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Attestations: []*ethpb.Attestation{att},
},
}
err := beaconState.SetSlot(beaconState.Slot() + params.BeaconConfig().MinAttestationInclusionDelay)
if err != nil {
t.Fatal(err)
}
cfc := beaconState.CurrentJustifiedCheckpoint()
cfc.Root = []byte("hello-world")
if err := beaconState.SetCurrentJustifiedCheckpoint(cfc); err != nil {
t.Fatal(err)
}
if err := beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
expected := "failed to verify aggregation bitfield: wanted participants bitfield length 3, got: 4"
_, err = blocks.ProcessAttestations(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), expected) {
t.Errorf("Did not receive wanted error")
}
}
func TestProcessAttestations_OK(t *testing.T) {
beaconState, privKeys := testutil.DeterministicGenesisState(t, 100)
aggBits := bitfield.NewBitlist(3)
aggBits.SetBitAt(0, true)
var mockRoot [32]byte
copy(mockRoot[:], "hello-world")
att := &ethpb.Attestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0, Root: mockRoot[:]},
Target: &ethpb.Checkpoint{Epoch: 0, Root: mockRoot[:]},
},
AggregationBits: aggBits,
}
cfc := beaconState.CurrentJustifiedCheckpoint()
cfc.Root = mockRoot[:]
if err := beaconState.SetCurrentJustifiedCheckpoint(cfc); err != nil {
t.Fatal(err)
}
if err := beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
t.Error(err)
}
attestingIndices := attestationutil.AttestingIndices(att.AggregationBits, committee)
if err != nil {
t.Error(err)
}
sigs := make([]bls.Signature, len(attestingIndices))
for i, indice := range attestingIndices {
sb, err := helpers.ComputeDomainAndSign(beaconState, 0, att.Data, params.BeaconConfig().DomainBeaconAttester, privKeys[indice])
require.NoError(t, err)
sig, err := bls.SignatureFromBytes(sb)
require.NoError(t, err)
sigs[i] = sig
}
att.Signature = bls.AggregateSignatures(sigs).Marshal()[:]
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Attestations: []*ethpb.Attestation{att},
},
}
err = beaconState.SetSlot(beaconState.Slot() + params.BeaconConfig().MinAttestationInclusionDelay)
if err != nil {
t.Fatal(err)
}
if _, err := blocks.ProcessAttestations(context.Background(), beaconState, block.Body); err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestProcessAggregatedAttestation_OverlappingBits(t *testing.T) {
beaconState, privKeys := testutil.DeterministicGenesisState(t, 100)
data := &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0, Root: []byte("hello-world")},
Target: &ethpb.Checkpoint{Epoch: 0, Root: []byte("hello-world")},
}
aggBits1 := bitfield.NewBitlist(4)
aggBits1.SetBitAt(0, true)
aggBits1.SetBitAt(1, true)
aggBits1.SetBitAt(2, true)
att1 := &ethpb.Attestation{
Data: data,
AggregationBits: aggBits1,
}
cfc := beaconState.CurrentJustifiedCheckpoint()
cfc.Root = []byte("hello-world")
if err := beaconState.SetCurrentJustifiedCheckpoint(cfc); err != nil {
t.Fatal(err)
}
if err := beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att1.Data.Slot, att1.Data.CommitteeIndex)
if err != nil {
t.Error(err)
}
attestingIndices1 := attestationutil.AttestingIndices(att1.AggregationBits, committee)
if err != nil {
t.Fatal(err)
}
sigs := make([]bls.Signature, len(attestingIndices1))
for i, indice := range attestingIndices1 {
sb, err := helpers.ComputeDomainAndSign(beaconState, 0, att1.Data, params.BeaconConfig().DomainBeaconAttester, privKeys[indice])
require.NoError(t, err)
sig, err := bls.SignatureFromBytes(sb)
require.NoError(t, err)
sigs[i] = sig
}
att1.Signature = bls.AggregateSignatures(sigs).Marshal()[:]
aggBits2 := bitfield.NewBitlist(4)
aggBits2.SetBitAt(1, true)
aggBits2.SetBitAt(2, true)
aggBits2.SetBitAt(3, true)
att2 := &ethpb.Attestation{
Data: data,
AggregationBits: aggBits2,
}
committee, err = helpers.BeaconCommitteeFromState(beaconState, att2.Data.Slot, att2.Data.CommitteeIndex)
if err != nil {
t.Error(err)
}
attestingIndices2 := attestationutil.AttestingIndices(att2.AggregationBits, committee)
if err != nil {
t.Fatal(err)
}
sigs = make([]bls.Signature, len(attestingIndices2))
for i, indice := range attestingIndices2 {
sb, err := helpers.ComputeDomainAndSign(beaconState, 0, att2.Data, params.BeaconConfig().DomainBeaconAttester, privKeys[indice])
require.NoError(t, err)
sig, err := bls.SignatureFromBytes(sb)
require.NoError(t, err)
sigs[i] = sig
}
att2.Signature = bls.AggregateSignatures(sigs).Marshal()[:]
if _, err = attaggregation.AggregatePair(att1, att2); err != aggregation.ErrBitsOverlap {
t.Error("Did not receive wanted error")
}
}
func TestProcessAggregatedAttestation_NoOverlappingBits(t *testing.T) {
beaconState, privKeys := testutil.DeterministicGenesisState(t, 300)
var mockRoot [32]byte
copy(mockRoot[:], "hello-world")
data := &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0, Root: mockRoot[:]},
Target: &ethpb.Checkpoint{Epoch: 0, Root: mockRoot[:]},
}
aggBits1 := bitfield.NewBitlist(9)
aggBits1.SetBitAt(0, true)
aggBits1.SetBitAt(1, true)
att1 := &ethpb.Attestation{
Data: data,
AggregationBits: aggBits1,
}
cfc := beaconState.CurrentJustifiedCheckpoint()
cfc.Root = mockRoot[:]
if err := beaconState.SetCurrentJustifiedCheckpoint(cfc); err != nil {
t.Fatal(err)
}
if err := beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att1.Data.Slot, att1.Data.CommitteeIndex)
if err != nil {
t.Error(err)
}
attestingIndices1 := attestationutil.AttestingIndices(att1.AggregationBits, committee)
if err != nil {
t.Fatal(err)
}
sigs := make([]bls.Signature, len(attestingIndices1))
for i, indice := range attestingIndices1 {
sb, err := helpers.ComputeDomainAndSign(beaconState, 0, data, params.BeaconConfig().DomainBeaconAttester, privKeys[indice])
require.NoError(t, err)
sig, err := bls.SignatureFromBytes(sb)
require.NoError(t, err)
sigs[i] = sig
}
att1.Signature = bls.AggregateSignatures(sigs).Marshal()[:]
aggBits2 := bitfield.NewBitlist(9)
aggBits2.SetBitAt(2, true)
aggBits2.SetBitAt(3, true)
att2 := &ethpb.Attestation{
Data: data,
AggregationBits: aggBits2,
}
committee, err = helpers.BeaconCommitteeFromState(beaconState, att2.Data.Slot, att2.Data.CommitteeIndex)
if err != nil {
t.Error(err)
}
attestingIndices2 := attestationutil.AttestingIndices(att2.AggregationBits, committee)
if err != nil {
t.Fatal(err)
}
sigs = make([]bls.Signature, len(attestingIndices2))
for i, indice := range attestingIndices2 {
sb, err := helpers.ComputeDomainAndSign(beaconState, 0, att2.Data, params.BeaconConfig().DomainBeaconAttester, privKeys[indice])
require.NoError(t, err)
sig, err := bls.SignatureFromBytes(sb)
require.NoError(t, err)
sigs[i] = sig
}
att2.Signature = bls.AggregateSignatures(sigs).Marshal()[:]
aggregatedAtt, err := attaggregation.AggregatePair(att1, att2)
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Attestations: []*ethpb.Attestation{aggregatedAtt},
},
}
err = beaconState.SetSlot(beaconState.Slot() + params.BeaconConfig().MinAttestationInclusionDelay)
if err != nil {
t.Fatal(err)
}
if _, err := blocks.ProcessAttestations(context.Background(), beaconState, block.Body); err != nil {
t.Error(err)
}
}
func TestProcessAttestationsNoVerify_IncorrectSlotTargetEpoch(t *testing.T) {
beaconState, _ := testutil.DeterministicGenesisState(t, 1)
att := &ethpb.Attestation{
Data: &ethpb.AttestationData{
Slot: params.BeaconConfig().SlotsPerEpoch,
Target: &ethpb.Checkpoint{},
},
}
wanted := fmt.Sprintf("data slot is not in the same epoch as target %d != %d", helpers.SlotToEpoch(att.Data.Slot), att.Data.Target.Epoch)
_, err := blocks.ProcessAttestationNoVerify(context.TODO(), beaconState, att)
if err == nil || err.Error() != wanted {
t.Error("Did not get wanted error")
}
}
func TestProcessAttestationsNoVerify_OK(t *testing.T) {
// Attestation with an empty signature
beaconState, _ := testutil.DeterministicGenesisState(t, 100)
aggBits := bitfield.NewBitlist(3)
aggBits.SetBitAt(1, true)
var mockRoot [32]byte
copy(mockRoot[:], "hello-world")
att := &ethpb.Attestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0, Root: mockRoot[:]},
Target: &ethpb.Checkpoint{Epoch: 0},
},
AggregationBits: aggBits,
}
zeroSig := [96]byte{}
att.Signature = zeroSig[:]
err := beaconState.SetSlot(beaconState.Slot() + params.BeaconConfig().MinAttestationInclusionDelay)
if err != nil {
t.Fatal(err)
}
ckp := beaconState.CurrentJustifiedCheckpoint()
copy(ckp.Root, "hello-world")
if err := beaconState.SetCurrentJustifiedCheckpoint(ckp); err != nil {
t.Fatal(err)
}
if err := beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}); err != nil {
t.Fatal(err)
}
if _, err := blocks.ProcessAttestationNoVerify(context.TODO(), beaconState, att); err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestProcessAttestationsNoVerify_BadAttIdx(t *testing.T) {
beaconState, _ := testutil.DeterministicGenesisState(t, 100)
aggBits := bitfield.NewBitlist(3)
aggBits.SetBitAt(1, true)
var mockRoot [32]byte
copy(mockRoot[:], "hello-world")
att := &ethpb.Attestation{
Data: &ethpb.AttestationData{
CommitteeIndex: 100,
Source: &ethpb.Checkpoint{Epoch: 0, Root: mockRoot[:]},
Target: &ethpb.Checkpoint{Epoch: 0},
},
AggregationBits: aggBits,
}
zeroSig := [96]byte{}
att.Signature = zeroSig[:]
require.NoError(t, beaconState.SetSlot(beaconState.Slot()+params.BeaconConfig().MinAttestationInclusionDelay))
ckp := beaconState.CurrentJustifiedCheckpoint()
copy(ckp.Root, "hello-world")
require.NoError(t, beaconState.SetCurrentJustifiedCheckpoint(ckp))
require.NoError(t, beaconState.SetCurrentEpochAttestations([]*pb.PendingAttestation{}))
_, err := blocks.ProcessAttestationNoVerify(context.TODO(), beaconState, att)
require.ErrorContains(t, "committee index 100 >= committee count 1", err)
}
func TestConvertToIndexed_OK(t *testing.T) {
helpers.ClearCache()
validators := make([]*ethpb.Validator, 2*params.BeaconConfig().SlotsPerEpoch)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
}
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 5,
Validators: validators,
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
if err != nil {
t.Fatal(err)
}
tests := []struct {
aggregationBitfield bitfield.Bitlist
wantedAttestingIndices []uint64
}{
{
aggregationBitfield: bitfield.Bitlist{0x07},
wantedAttestingIndices: []uint64{43, 47},
},
{
aggregationBitfield: bitfield.Bitlist{0x03},
wantedAttestingIndices: []uint64{47},
},
{
aggregationBitfield: bitfield.Bitlist{0x01},
wantedAttestingIndices: []uint64{},
},
}
var sig [96]byte
copy(sig[:], "signed")
attestation := &ethpb.Attestation{
Signature: sig[:],
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0},
Target: &ethpb.Checkpoint{Epoch: 0},
},
}
for _, tt := range tests {
attestation.AggregationBits = tt.aggregationBitfield
wanted := &ethpb.IndexedAttestation{
AttestingIndices: tt.wantedAttestingIndices,
Data: attestation.Data,
Signature: attestation.Signature,
}
committee, err := helpers.BeaconCommitteeFromState(state, attestation.Data.Slot, attestation.Data.CommitteeIndex)
if err != nil {
t.Error(err)
}
ia := attestationutil.ConvertToIndexed(context.Background(), attestation, committee)
if !reflect.DeepEqual(wanted, ia) {
t.Error("convert attestation to indexed attestation didn't result as wanted")
}
}
}
func TestVerifyIndexedAttestation_OK(t *testing.T) {
numOfValidators := 4 * params.BeaconConfig().SlotsPerEpoch
validators := make([]*ethpb.Validator, numOfValidators)
_, keys, err := testutil.DeterministicDepositsAndKeys(numOfValidators)
if err != nil {
t.Fatal(err)
}
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
PublicKey: keys[i].PublicKey().Marshal(),
}
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 5,
Validators: validators,
Fork: &pb.Fork{
Epoch: 0,
CurrentVersion: params.BeaconConfig().GenesisForkVersion,
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
if err != nil {
t.Fatal(err)
}
tests := []struct {
attestation *ethpb.IndexedAttestation
}{
{attestation: &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Target: &ethpb.Checkpoint{
Epoch: 2,
},
},
AttestingIndices: []uint64{1},
}},
{attestation: &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Target: &ethpb.Checkpoint{
Epoch: 1,
},
},
AttestingIndices: []uint64{47, 99, 101},
}},
{attestation: &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Target: &ethpb.Checkpoint{
Epoch: 4,
},
},
AttestingIndices: []uint64{21, 72},
}},
{attestation: &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Target: &ethpb.Checkpoint{
Epoch: 7,
},
},
AttestingIndices: []uint64{100, 121, 122},
}},
}
for _, tt := range tests {
var sig []bls.Signature
for _, idx := range tt.attestation.AttestingIndices {
sb, err := helpers.ComputeDomainAndSign(state, tt.attestation.Data.Target.Epoch, tt.attestation.Data, params.BeaconConfig().DomainBeaconAttester, keys[idx])
require.NoError(t, err)
validatorSig, err := bls.SignatureFromBytes(sb)
require.NoError(t, err)
sig = append(sig, validatorSig)
}
aggSig := bls.AggregateSignatures(sig)
marshalledSig := aggSig.Marshal()
tt.attestation.Signature = marshalledSig
err = blocks.VerifyIndexedAttestation(context.Background(), state, tt.attestation)
if err != nil {
t.Errorf("failed to verify indexed attestation: %v", err)
}
}
}
func TestValidateIndexedAttestation_AboveMaxLength(t *testing.T) {
indexedAtt1 := &ethpb.IndexedAttestation{
AttestingIndices: make([]uint64, params.BeaconConfig().MaxValidatorsPerCommittee+5),
}
for i := uint64(0); i < params.BeaconConfig().MaxValidatorsPerCommittee+5; i++ {
indexedAtt1.AttestingIndices[i] = i
indexedAtt1.Data = &ethpb.AttestationData{
Target: &ethpb.Checkpoint{
Epoch: i,
},
}
}
want := "validator indices count exceeds MAX_VALIDATORS_PER_COMMITTEE"
err := blocks.VerifyIndexedAttestation(context.Background(), &stateTrie.BeaconState{}, indexedAtt1)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected verification to fail return false, received: %v", err)
}
}
func TestVerifyAttestations_VerifiesMultipleAttestations(t *testing.T) {
ctx := context.Background()
numOfValidators := 4 * params.BeaconConfig().SlotsPerEpoch
validators := make([]*ethpb.Validator, numOfValidators)
_, keys, err := testutil.DeterministicDepositsAndKeys(numOfValidators)
if err != nil {
t.Fatal(err)
}
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
PublicKey: keys[i].PublicKey().Marshal(),
}
}
st, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 5,
Validators: validators,
Fork: &pb.Fork{
Epoch: 0,
CurrentVersion: params.BeaconConfig().GenesisForkVersion,
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
comm1, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 0 /*committeeIndex*/)
if err != nil {
t.Fatal(err)
}
att1 := &ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm1))),
Data: &ethpb.AttestationData{
Slot: 1,
CommitteeIndex: 0,
},
Signature: nil,
}
domain, err := helpers.Domain(st.Fork(), st.Fork().Epoch, params.BeaconConfig().DomainBeaconAttester, st.GenesisValidatorRoot())
if err != nil {
t.Fatal(err)
}
root, err := helpers.ComputeSigningRoot(att1.Data, domain)
if err != nil {
t.Fatal(err)
}
var sigs []bls.Signature
for i, u := range comm1 {
att1.AggregationBits.SetBitAt(uint64(i), true)
sigs = append(sigs, keys[u].Sign(root[:]))
}
att1.Signature = bls.AggregateSignatures(sigs).Marshal()
comm2, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 1 /*committeeIndex*/)
if err != nil {
t.Fatal(err)
}
att2 := &ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm2))),
Data: &ethpb.AttestationData{
Slot: 1,
CommitteeIndex: 1,
},
Signature: nil,
}
root, err = helpers.ComputeSigningRoot(att2.Data, domain)
if err != nil {
t.Fatal(err)
}
sigs = nil
for i, u := range comm2 {
att2.AggregationBits.SetBitAt(uint64(i), true)
sigs = append(sigs, keys[u].Sign(root[:]))
}
att2.Signature = bls.AggregateSignatures(sigs).Marshal()
if err := blocks.VerifyAttestations(ctx, st, []*ethpb.Attestation{att1, att2}); err != nil {
t.Fatal(err)
}
}
func TestVerifyAttestations_HandlesPlannedFork(t *testing.T) {
// In this test, att1 is from the prior fork and att2 is from the new fork.
ctx := context.Background()
numOfValidators := 4 * params.BeaconConfig().SlotsPerEpoch
validators := make([]*ethpb.Validator, numOfValidators)
_, keys, err := testutil.DeterministicDepositsAndKeys(numOfValidators)
if err != nil {
t.Fatal(err)
}
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
PublicKey: keys[i].PublicKey().Marshal(),
}
}
st, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 35,
Validators: validators,
Fork: &pb.Fork{
Epoch: 1,
CurrentVersion: []byte{0, 1, 2, 3},
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
comm1, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 0 /*committeeIndex*/)
if err != nil {
t.Fatal(err)
}
att1 := &ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm1))),
Data: &ethpb.AttestationData{
Slot: 1,
CommitteeIndex: 0,
},
Signature: nil,
}
prevDomain, err := helpers.Domain(st.Fork(), st.Fork().Epoch-1, params.BeaconConfig().DomainBeaconAttester, st.GenesisValidatorRoot())
if err != nil {
t.Fatal(err)
}
root, err := helpers.ComputeSigningRoot(att1.Data, prevDomain)
if err != nil {
t.Fatal(err)
}
var sigs []bls.Signature
for i, u := range comm1 {
att1.AggregationBits.SetBitAt(uint64(i), true)
sigs = append(sigs, keys[u].Sign(root[:]))
}
att1.Signature = bls.AggregateSignatures(sigs).Marshal()
comm2, err := helpers.BeaconCommitteeFromState(st, 1*params.BeaconConfig().SlotsPerEpoch+1 /*slot*/, 1 /*committeeIndex*/)
if err != nil {
t.Fatal(err)
}
att2 := &ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm2))),
Data: &ethpb.AttestationData{
Slot: 1*params.BeaconConfig().SlotsPerEpoch + 1,
CommitteeIndex: 1,
},
Signature: nil,
}
currDomain, err := helpers.Domain(st.Fork(), st.Fork().Epoch, params.BeaconConfig().DomainBeaconAttester, st.GenesisValidatorRoot())
root, err = helpers.ComputeSigningRoot(att2.Data, currDomain)
if err != nil {
t.Fatal(err)
}
sigs = nil
for i, u := range comm2 {
att2.AggregationBits.SetBitAt(uint64(i), true)
sigs = append(sigs, keys[u].Sign(root[:]))
}
att2.Signature = bls.AggregateSignatures(sigs).Marshal()
if err := blocks.VerifyAttestations(ctx, st, []*ethpb.Attestation{att1, att2}); err != nil {
t.Fatal(err)
}
}
func TestRetrieveAttestationSignatureSet_VerifiesMultipleAttestations(t *testing.T) {
ctx := context.Background()
numOfValidators := 4 * params.BeaconConfig().SlotsPerEpoch
validators := make([]*ethpb.Validator, numOfValidators)
_, keys, err := testutil.DeterministicDepositsAndKeys(numOfValidators)
if err != nil {
t.Fatal(err)
}
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
PublicKey: keys[i].PublicKey().Marshal(),
}
}
st, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Slot: 5,
Validators: validators,
Fork: &pb.Fork{
Epoch: 0,
CurrentVersion: params.BeaconConfig().GenesisForkVersion,
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
comm1, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 0 /*committeeIndex*/)
if err != nil {
t.Fatal(err)
}
att1 := &ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm1))),
Data: &ethpb.AttestationData{
Slot: 1,
CommitteeIndex: 0,
},
Signature: nil,
}
domain, err := helpers.Domain(st.Fork(), st.Fork().Epoch, params.BeaconConfig().DomainBeaconAttester, st.GenesisValidatorRoot())
if err != nil {
t.Fatal(err)
}
root, err := helpers.ComputeSigningRoot(att1.Data, domain)
if err != nil {
t.Fatal(err)
}
var sigs []bls.Signature
for i, u := range comm1 {
att1.AggregationBits.SetBitAt(uint64(i), true)
sigs = append(sigs, keys[u].Sign(root[:]))
}
att1.Signature = bls.AggregateSignatures(sigs).Marshal()
comm2, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 1 /*committeeIndex*/)
if err != nil {
t.Fatal(err)
}
att2 := &ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm2))),
Data: &ethpb.AttestationData{
Slot: 1,
CommitteeIndex: 1,
},
Signature: nil,
}
root, err = helpers.ComputeSigningRoot(att2.Data, domain)
if err != nil {
t.Fatal(err)
}
sigs = nil
for i, u := range comm2 {
att2.AggregationBits.SetBitAt(uint64(i), true)
sigs = append(sigs, keys[u].Sign(root[:]))
}
att2.Signature = bls.AggregateSignatures(sigs).Marshal()
set, err := blocks.AttestationSignatureSet(ctx, st, []*ethpb.Attestation{att1, att2})
if err != nil {
t.Fatal(err)
}
verified, err := set.Verify()
if err != nil {
t.Fatal(err)
}
if !verified {
t.Error("Multiple signatures were unable to be verified.")
}
}

View File

@@ -0,0 +1,129 @@
package blocks
import (
"context"
"sort"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/attestationutil"
"github.com/prysmaticlabs/prysm/shared/sliceutil"
)
// ProcessAttesterSlashings is one of the operations performed
// on each processed beacon block to slash attesters based on
// Casper FFG slashing conditions if any slashable events occurred.
//
// Spec pseudocode definition:
// def process_attester_slashing(state: BeaconState, attester_slashing: AttesterSlashing) -> None:
// attestation_1 = attester_slashing.attestation_1
// attestation_2 = attester_slashing.attestation_2
// assert is_slashable_attestation_data(attestation_1.data, attestation_2.data)
// assert is_valid_indexed_attestation(state, attestation_1)
// assert is_valid_indexed_attestation(state, attestation_2)
//
// slashed_any = False
// indices = set(attestation_1.attesting_indices).intersection(attestation_2.attesting_indices)
// for index in sorted(indices):
// if is_slashable_validator(state.validators[index], get_current_epoch(state)):
// slash_validator(state, index)
// slashed_any = True
// assert slashed_any
func ProcessAttesterSlashings(
ctx context.Context,
beaconState *stateTrie.BeaconState,
body *ethpb.BeaconBlockBody,
) (*stateTrie.BeaconState, error) {
for idx, slashing := range body.AttesterSlashings {
if err := VerifyAttesterSlashing(ctx, beaconState, slashing); err != nil {
return nil, errors.Wrapf(err, "could not verify attester slashing %d", idx)
}
slashableIndices := slashableAttesterIndices(slashing)
sort.SliceStable(slashableIndices, func(i, j int) bool {
return slashableIndices[i] < slashableIndices[j]
})
currentEpoch := helpers.SlotToEpoch(beaconState.Slot())
var err error
var slashedAny bool
var val *ethpb.Validator
for _, validatorIndex := range slashableIndices {
val, err = beaconState.ValidatorAtIndex(validatorIndex)
if err != nil {
return nil, err
}
if helpers.IsSlashableValidator(val, currentEpoch) {
beaconState, err = v.SlashValidator(beaconState, validatorIndex)
if err != nil {
return nil, errors.Wrapf(err, "could not slash validator index %d",
validatorIndex)
}
slashedAny = true
}
}
if !slashedAny {
return nil, errors.New("unable to slash any validator despite confirmed attester slashing")
}
}
return beaconState, nil
}
// VerifyAttesterSlashing validates the attestation data in both attestations in the slashing object.
func VerifyAttesterSlashing(ctx context.Context, beaconState *stateTrie.BeaconState, slashing *ethpb.AttesterSlashing) error {
if slashing == nil {
return errors.New("nil slashing")
}
if slashing.Attestation_1 == nil || slashing.Attestation_2 == nil {
return errors.New("nil attestation")
}
if slashing.Attestation_1.Data == nil || slashing.Attestation_2.Data == nil {
return errors.New("nil attestation data")
}
att1 := slashing.Attestation_1
att2 := slashing.Attestation_2
data1 := att1.Data
data2 := att2.Data
if !IsSlashableAttestationData(data1, data2) {
return errors.New("attestations are not slashable")
}
if err := VerifyIndexedAttestation(ctx, beaconState, att1); err != nil {
return errors.Wrap(err, "could not validate indexed attestation")
}
if err := VerifyIndexedAttestation(ctx, beaconState, att2); err != nil {
return errors.Wrap(err, "could not validate indexed attestation")
}
return nil
}
// IsSlashableAttestationData verifies a slashing against the Casper Proof of Stake FFG rules.
//
// Spec pseudocode definition:
// def is_slashable_attestation_data(data_1: AttestationData, data_2: AttestationData) -> bool:
// """
// Check if ``data_1`` and ``data_2`` are slashable according to Casper FFG rules.
// """
// return (
// # Double vote
// (data_1 != data_2 and data_1.target.epoch == data_2.target.epoch) or
// # Surround vote
// (data_1.source.epoch < data_2.source.epoch and data_2.target.epoch < data_1.target.epoch)
// )
func IsSlashableAttestationData(data1 *ethpb.AttestationData, data2 *ethpb.AttestationData) bool {
if data1 == nil || data2 == nil || data1.Target == nil || data2.Target == nil || data1.Source == nil || data2.Source == nil {
return false
}
isDoubleVote := !attestationutil.AttDataIsEqual(data1, data2) && data1.Target.Epoch == data2.Target.Epoch
isSurroundVote := data1.Source.Epoch < data2.Source.Epoch && data2.Target.Epoch < data1.Target.Epoch
return isDoubleVote || isSurroundVote
}
func slashableAttesterIndices(slashing *ethpb.AttesterSlashing) []uint64 {
if slashing == nil || slashing.Attestation_1 == nil || slashing.Attestation_2 == nil {
return nil
}
indices1 := slashing.Attestation_1.AttestingIndices
indices2 := slashing.Attestation_2.AttestingIndices
return sliceutil.IntersectionUint64(indices1, indices2)
}

View File

@@ -0,0 +1,201 @@
package blocks_test
import (
"context"
"fmt"
"strings"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
)
func TestSlashableAttestationData_CanSlash(t *testing.T) {
att1 := &ethpb.AttestationData{
Target: &ethpb.Checkpoint{Epoch: 1},
Source: &ethpb.Checkpoint{Root: []byte{'A'}},
}
att2 := &ethpb.AttestationData{
Target: &ethpb.Checkpoint{Epoch: 1},
Source: &ethpb.Checkpoint{Root: []byte{'B'}},
}
if !blocks.IsSlashableAttestationData(att1, att2) {
t.Error("atts should have been slashable")
}
att1.Target.Epoch = 4
att1.Source.Epoch = 2
att2.Source.Epoch = 3
if !blocks.IsSlashableAttestationData(att1, att2) {
t.Error("atts should have been slashable")
}
}
func TestProcessAttesterSlashings_DataNotSlashable(t *testing.T) {
slashings := []*ethpb.AttesterSlashing{
{
Attestation_1: &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0},
Target: &ethpb.Checkpoint{Epoch: 0},
},
},
Attestation_2: &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 1},
Target: &ethpb.Checkpoint{Epoch: 1},
},
},
},
}
registry := []*ethpb.Validator{}
currentSlot := uint64(0)
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Slot: currentSlot,
})
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
AttesterSlashings: slashings,
},
}
want := fmt.Sprint("attestations are not slashable")
_, err = blocks.ProcessAttesterSlashings(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessAttesterSlashings_IndexedAttestationFailedToVerify(t *testing.T) {
registry := []*ethpb.Validator{}
currentSlot := uint64(0)
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Slot: currentSlot,
})
if err != nil {
t.Fatal(err)
}
slashings := []*ethpb.AttesterSlashing{
{
Attestation_1: &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 1},
Target: &ethpb.Checkpoint{Epoch: 0},
},
AttestingIndices: make([]uint64, params.BeaconConfig().MaxValidatorsPerCommittee+1),
},
Attestation_2: &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0},
Target: &ethpb.Checkpoint{Epoch: 0},
},
AttestingIndices: make([]uint64, params.BeaconConfig().MaxValidatorsPerCommittee+1),
},
},
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
AttesterSlashings: slashings,
},
}
want := fmt.Sprint("validator indices count exceeds MAX_VALIDATORS_PER_COMMITTEE")
_, err = blocks.ProcessAttesterSlashings(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) {
beaconState, privKeys := testutil.DeterministicGenesisState(t, 100)
for _, vv := range beaconState.Validators() {
vv.WithdrawableEpoch = 1 * params.BeaconConfig().SlotsPerEpoch
}
att1 := &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 1},
Target: &ethpb.Checkpoint{Epoch: 0},
},
AttestingIndices: []uint64{0, 1},
}
domain, err := helpers.Domain(beaconState.Fork(), 0, params.BeaconConfig().DomainBeaconAttester, beaconState.GenesisValidatorRoot())
if err != nil {
t.Fatal(err)
}
signingRoot, err := helpers.ComputeSigningRoot(att1.Data, domain)
if err != nil {
t.Errorf("Could not get signing root of beacon block header: %v", err)
}
sig0 := privKeys[0].Sign(signingRoot[:])
sig1 := privKeys[1].Sign(signingRoot[:])
aggregateSig := bls.AggregateSignatures([]bls.Signature{sig0, sig1})
att1.Signature = aggregateSig.Marshal()[:]
att2 := &ethpb.IndexedAttestation{
Data: &ethpb.AttestationData{
Source: &ethpb.Checkpoint{Epoch: 0},
Target: &ethpb.Checkpoint{Epoch: 0},
},
AttestingIndices: []uint64{0, 1},
}
signingRoot, err = helpers.ComputeSigningRoot(att2.Data, domain)
if err != nil {
t.Errorf("Could not get signing root of beacon block header: %v", err)
}
sig0 = privKeys[0].Sign(signingRoot[:])
sig1 = privKeys[1].Sign(signingRoot[:])
aggregateSig = bls.AggregateSignatures([]bls.Signature{sig0, sig1})
att2.Signature = aggregateSig.Marshal()[:]
slashings := []*ethpb.AttesterSlashing{
{
Attestation_1: att1,
Attestation_2: att2,
},
}
currentSlot := 2 * params.BeaconConfig().SlotsPerEpoch
if err := beaconState.SetSlot(currentSlot); err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
AttesterSlashings: slashings,
},
}
newState, err := blocks.ProcessAttesterSlashings(context.Background(), beaconState, block.Body)
if err != nil {
t.Fatal(err)
}
newRegistry := newState.Validators()
// Given the intersection of slashable indices is [1], only validator
// at index 1 should be slashed and exited. We confirm this below.
if newRegistry[1].ExitEpoch != beaconState.Validators()[1].ExitEpoch {
t.Errorf(
`
Expected validator at index 1's exit epoch to match
%d, received %d instead
`,
beaconState.Validators()[1].ExitEpoch,
newRegistry[1].ExitEpoch,
)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -25,12 +25,8 @@ func TestFuzzProcessAttestationNoVerify_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(att)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
if _, err = ProcessAttestationNoVerify(ctx, s, att); err != nil {
t.Log(err)
}
_, err = ProcessAttestationNoVerify(ctx, s, att)
_ = err
}
}
@@ -44,12 +40,8 @@ func TestFuzzProcessBlockHeader_10000(t *testing.T) {
fuzzer.Fuzz(block)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
if _, err = ProcessBlockHeader(s, block); err != nil {
t.Log(err)
}
_, err = ProcessBlockHeader(s, block)
_ = err
}
}
@@ -70,13 +62,9 @@ func TestFuzzverifyDepositDataSigningRoot_10000(t *testing.T) {
fuzzer.Fuzz(&p)
fuzzer.Fuzz(&s)
fuzzer.Fuzz(&d)
if err := verifySignature(ba, pubkey[:], sig[:], domain[:]); err != nil {
t.Log(err)
}
if err := verifySignature(ba, p, s, d); err != nil {
t.Log(err)
}
err := verifySignature(ba, pubkey[:], sig[:], domain[:])
err = verifySignature(ba, p, s, d)
_ = err
}
}
@@ -102,8 +90,8 @@ func TestFuzzareEth1DataEqual_10000(t *testing.T) {
for i := 0; i < 10000; i++ {
fuzzer.Fuzz(eth1data)
fuzzer.Fuzz(eth1data2)
areEth1DataEqual(eth1data, eth1data2)
areEth1DataEqual(eth1data, eth1data)
AreEth1DataEqual(eth1data, eth1data2)
AreEth1DataEqual(eth1data, eth1data)
}
}
@@ -117,12 +105,8 @@ func TestFuzzEth1DataHasEnoughSupport_10000(t *testing.T) {
s, err := beaconstate.InitializeFromProto(&ethereum_beacon_p2p_v1.BeaconState{
Eth1DataVotes: stateVotes,
})
if err != nil {
t.Log(err)
}
if _, err := Eth1DataHasEnoughSupport(s, eth1data); err != nil {
t.Log(err)
}
_, err = Eth1DataHasEnoughSupport(s, eth1data)
_ = err
}
}
@@ -136,12 +120,8 @@ func TestFuzzProcessBlockHeaderNoVerify_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(block)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
if _, err = ProcessBlockHeaderNoVerify(s, block); err != nil {
t.Log(err)
}
_, err = ProcessBlockHeaderNoVerify(s, block)
_ = err
}
}
@@ -154,9 +134,6 @@ func TestFuzzProcessRandao_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessRandao(s, blockBody)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
@@ -173,9 +150,6 @@ func TestFuzzProcessRandaoNoVerify_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessRandaoNoVerify(s, blockBody)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
@@ -192,9 +166,6 @@ func TestFuzzProcessProposerSlashings_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessProposerSlashings(ctx, s, blockBody)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
@@ -210,12 +181,8 @@ func TestFuzzVerifyProposerSlashing_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(proposerSlashing)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
if err := VerifyProposerSlashing(s, proposerSlashing); err != nil {
t.Log(err)
}
err = VerifyProposerSlashing(s, proposerSlashing)
_ = err
}
}
@@ -228,9 +195,6 @@ func TestFuzzProcessAttesterSlashings_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessAttesterSlashings(ctx, s, blockBody)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
@@ -247,12 +211,8 @@ func TestFuzzVerifyAttesterSlashing_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(attesterSlashing)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
if err := VerifyAttesterSlashing(ctx, s, attesterSlashing); err != nil {
t.Log(err)
}
err = VerifyAttesterSlashing(ctx, s, attesterSlashing)
_ = err
}
}
@@ -287,9 +247,6 @@ func TestFuzzProcessAttestations_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessAttestations(ctx, s, blockBody)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
@@ -306,9 +263,6 @@ func TestFuzzProcessAttestationsNoVerify_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessAttestationsNoVerify(ctx, s, blockBody)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
@@ -325,9 +279,6 @@ func TestFuzzProcessAttestation_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(attestation)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessAttestation(ctx, s, attestation)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, attestation)
@@ -344,12 +295,8 @@ func TestFuzzVerifyIndexedAttestationn_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(idxAttestation)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
if err := VerifyIndexedAttestation(ctx, s, idxAttestation); err != nil {
t.Log(err)
}
err = VerifyIndexedAttestation(ctx, s, idxAttestation)
_ = err
}
}
@@ -362,12 +309,8 @@ func TestFuzzVerifyAttestation_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(attestation)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
if err := VerifyAttestation(ctx, s, attestation); err != nil {
t.Log(err)
}
err = VerifyAttestation(ctx, s, attestation)
_ = err
}
}
@@ -380,10 +323,7 @@ func TestFuzzProcessDeposits_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessDeposits(ctx, s, blockBody)
r, err := ProcessDeposits(ctx, s, blockBody.Deposits)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
}
@@ -400,10 +340,7 @@ func TestFuzzProcessPreGenesisDeposit_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(deposit)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessPreGenesisDeposit(ctx, s, deposit)
r, err := ProcessPreGenesisDeposits(ctx, s, []*eth.Deposit{deposit})
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, deposit)
}
@@ -419,10 +356,7 @@ func TestFuzzProcessDeposit_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(deposit)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessDeposit(s, deposit)
r, err := ProcessDeposit(s, deposit, true)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, deposit)
}
@@ -437,12 +371,8 @@ func TestFuzzverifyDeposit_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(deposit)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
if err := verifyDeposit(s, deposit); err != nil {
t.Log(err)
}
err = verifyDeposit(s, deposit)
_ = err
}
}
@@ -455,9 +385,6 @@ func TestFuzzProcessVoluntaryExits_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessVoluntaryExits(ctx, s, blockBody)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
@@ -473,9 +400,6 @@ func TestFuzzProcessVoluntaryExitsNoVerify_10000(t *testing.T) {
fuzzer.Fuzz(state)
fuzzer.Fuzz(blockBody)
s, err := beaconstate.InitializeFromProtoUnsafe(state)
if err != nil {
t.Log(err)
}
r, err := ProcessVoluntaryExitsNoVerify(s, blockBody)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, blockBody)
@@ -486,7 +410,7 @@ func TestFuzzProcessVoluntaryExitsNoVerify_10000(t *testing.T) {
func TestFuzzVerifyExit_10000(t *testing.T) {
fuzzer := fuzz.NewWithSeed(0)
ve := &eth.SignedVoluntaryExit{}
val := &eth.Validator{}
val := &beaconstate.ReadOnlyValidator{}
fork := &pb.Fork{}
var slot uint64
@@ -495,8 +419,7 @@ func TestFuzzVerifyExit_10000(t *testing.T) {
fuzzer.Fuzz(val)
fuzzer.Fuzz(fork)
fuzzer.Fuzz(&slot)
if err := VerifyExit(val, slot, fork, ve, params.BeaconConfig().ZeroHash[:]); err != nil {
t.Log(err)
}
err := VerifyExit(val, slot, fork, ve, params.BeaconConfig().ZeroHash[:])
_ = err
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -50,7 +50,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) {
if err != nil {
t.Errorf("Could not get signing root of beacon block header: %v", err)
}
aggSigs := []*bls.Signature{}
aggSigs := []bls.Signature{}
for _, index := range setA {
sig := privKeys[index].Sign(signingRoot[:])
aggSigs = append(aggSigs, sig)
@@ -70,7 +70,7 @@ func TestProcessAttesterSlashings_RegressionSlashableIndices(t *testing.T) {
if err != nil {
t.Errorf("Could not get signing root of beacon block header: %v", err)
}
aggSigs = []*bls.Signature{}
aggSigs = []bls.Signature{}
for _, index := range setB {
sig := privKeys[index].Sign(signingRoot[:])
aggSigs = append(aggSigs, sig)

View File

@@ -0,0 +1,272 @@
package blocks
import (
"context"
"fmt"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/depositutil"
"github.com/prysmaticlabs/prysm/shared/mathutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/trieutil"
)
// ProcessPreGenesisDeposits processes a deposit for the beacon state before chainstart.
func ProcessPreGenesisDeposits(
ctx context.Context,
beaconState *stateTrie.BeaconState,
deposits []*ethpb.Deposit,
) (*stateTrie.BeaconState, error) {
var err error
beaconState, err = ProcessDeposits(ctx, beaconState, deposits)
if err != nil {
return nil, errors.Wrap(err, "could not process deposit")
}
for _, deposit := range deposits {
pubkey := deposit.Data.PublicKey
index, ok := beaconState.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubkey))
if !ok {
return beaconState, nil
}
balance, err := beaconState.BalanceAtIndex(index)
if err != nil {
return nil, err
}
validator, err := beaconState.ValidatorAtIndex(index)
if err != nil {
return nil, err
}
validator.EffectiveBalance = mathutil.Min(balance-balance%params.BeaconConfig().EffectiveBalanceIncrement, params.BeaconConfig().MaxEffectiveBalance)
if validator.EffectiveBalance ==
params.BeaconConfig().MaxEffectiveBalance {
validator.ActivationEligibilityEpoch = 0
validator.ActivationEpoch = 0
}
if err := beaconState.UpdateValidatorAtIndex(index, validator); err != nil {
return nil, err
}
}
return beaconState, nil
}
// ProcessDeposits is one of the operations performed on each processed
// beacon block to verify queued validators from the Ethereum 1.0 Deposit Contract
// into the beacon chain.
//
// Spec pseudocode definition:
// For each deposit in block.body.deposits:
// process_deposit(state, deposit)
func ProcessDeposits(
ctx context.Context,
beaconState *stateTrie.BeaconState,
deposits []*ethpb.Deposit,
) (*stateTrie.BeaconState, error) {
var err error
domain, err := helpers.ComputeDomain(params.BeaconConfig().DomainDeposit, nil, nil)
if err != nil {
return nil, err
}
// Attempt to verify all deposit signatures at once, if this fails then fall back to processing
// individual deposits with signature verification enabled.
var verifySignature bool
if err := verifyDepositDataWithDomain(ctx, deposits, domain); err != nil {
log.WithError(err).Debug("Failed to verify deposit data, verifying signatures individually")
verifySignature = true
}
for _, deposit := range deposits {
if deposit == nil || deposit.Data == nil {
return nil, errors.New("got a nil deposit in block")
}
beaconState, err = ProcessDeposit(beaconState, deposit, verifySignature)
if err != nil {
return nil, errors.Wrapf(err, "could not process deposit from %#x", bytesutil.Trunc(deposit.Data.PublicKey))
}
}
return beaconState, nil
}
// ProcessDeposit takes in a deposit object and inserts it
// into the registry as a new validator or balance change.
//
// Spec pseudocode definition:
// def process_deposit(state: BeaconState, deposit: Deposit) -> None:
// # Verify the Merkle branch
// assert is_valid_merkle_branch(
// leaf=hash_tree_root(deposit.data),
// branch=deposit.proof,
// depth=DEPOSIT_CONTRACT_TREE_DEPTH + 1, # Add 1 for the List length mix-in
// index=state.eth1_deposit_index,
// root=state.eth1_data.deposit_root,
// )
//
// # Deposits must be processed in order
// state.eth1_deposit_index += 1
//
// pubkey = deposit.data.pubkey
// amount = deposit.data.amount
// validator_pubkeys = [v.pubkey for v in state.validators]
// if pubkey not in validator_pubkeys:
// # Verify the deposit signature (proof of possession) which is not checked by the deposit contract
// deposit_message = DepositMessage(
// pubkey=deposit.data.pubkey,
// withdrawal_credentials=deposit.data.withdrawal_credentials,
// amount=deposit.data.amount,
// )
// domain = compute_domain(DOMAIN_DEPOSIT) # Fork-agnostic domain since deposits are valid across forks
// signing_root = compute_signing_root(deposit_message, domain)
// if not bls.Verify(pubkey, signing_root, deposit.data.signature):
// return
//
// # Add validator and balance entries
// state.validators.append(get_validator_from_deposit(state, deposit))
// state.balances.append(amount)
// else:
// # Increase balance by deposit amount
// index = ValidatorIndex(validator_pubkeys.index(pubkey))
// increase_balance(state, index, amount)
func ProcessDeposit(beaconState *stateTrie.BeaconState, deposit *ethpb.Deposit, verifySignature bool) (*stateTrie.BeaconState, error) {
if err := verifyDeposit(beaconState, deposit); err != nil {
if deposit == nil || deposit.Data == nil {
return nil, err
}
return nil, errors.Wrapf(err, "could not verify deposit from %#x", bytesutil.Trunc(deposit.Data.PublicKey))
}
if err := beaconState.SetEth1DepositIndex(beaconState.Eth1DepositIndex() + 1); err != nil {
return nil, err
}
pubKey := deposit.Data.PublicKey
amount := deposit.Data.Amount
index, ok := beaconState.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubKey))
if !ok {
if verifySignature {
domain, err := helpers.ComputeDomain(params.BeaconConfig().DomainDeposit, nil, nil)
if err != nil {
return nil, err
}
depositSig := deposit.Data.Signature
if err := verifyDepositDataSigningRoot(deposit.Data, pubKey, depositSig, domain); err != nil {
// Ignore this error as in the spec pseudo code.
log.Debugf("Skipping deposit: could not verify deposit data signature: %v", err)
return beaconState, nil
}
}
effectiveBalance := amount - (amount % params.BeaconConfig().EffectiveBalanceIncrement)
if params.BeaconConfig().MaxEffectiveBalance < effectiveBalance {
effectiveBalance = params.BeaconConfig().MaxEffectiveBalance
}
if err := beaconState.AppendValidator(&ethpb.Validator{
PublicKey: pubKey,
WithdrawalCredentials: deposit.Data.WithdrawalCredentials,
ActivationEligibilityEpoch: params.BeaconConfig().FarFutureEpoch,
ActivationEpoch: params.BeaconConfig().FarFutureEpoch,
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
WithdrawableEpoch: params.BeaconConfig().FarFutureEpoch,
EffectiveBalance: effectiveBalance,
}); err != nil {
return nil, err
}
if err := beaconState.AppendBalance(amount); err != nil {
return nil, err
}
} else {
if err := helpers.IncreaseBalance(beaconState, index, amount); err != nil {
return nil, err
}
}
return beaconState, nil
}
func verifyDeposit(beaconState *stateTrie.BeaconState, deposit *ethpb.Deposit) error {
// Verify Merkle proof of deposit and deposit trie root.
if deposit == nil || deposit.Data == nil {
return errors.New("received nil deposit or nil deposit data")
}
eth1Data := beaconState.Eth1Data()
if eth1Data == nil {
return errors.New("received nil eth1data in the beacon state")
}
receiptRoot := eth1Data.DepositRoot
leaf, err := ssz.HashTreeRoot(deposit.Data)
if err != nil {
return errors.Wrap(err, "could not tree hash deposit data")
}
if ok := trieutil.VerifyMerkleBranch(
receiptRoot,
leaf[:],
int(beaconState.Eth1DepositIndex()),
deposit.Proof,
); !ok {
return fmt.Errorf(
"deposit merkle branch of deposit root did not verify for root: %#x",
receiptRoot,
)
}
return nil
}
// Deprecated: This method uses deprecated ssz.SigningRoot.
func verifyDepositDataSigningRoot(obj *ethpb.Deposit_Data, pub []byte, signature []byte, domain []byte) error {
return depositutil.VerifyDepositSignature(obj, domain)
}
func verifyDepositDataWithDomain(ctx context.Context, deps []*ethpb.Deposit, domain []byte) error {
if len(deps) == 0 {
return nil
}
pks := make([]bls.PublicKey, len(deps))
sigs := make([]bls.Signature, len(deps))
msgs := make([][32]byte, len(deps))
for i, dep := range deps {
if ctx.Err() != nil {
return ctx.Err()
}
if dep == nil || dep.Data == nil {
return errors.New("nil deposit")
}
dpk, err := bls.PublicKeyFromBytes(dep.Data.PublicKey)
if err != nil {
return err
}
pks[i] = dpk
dsig, err := bls.SignatureFromBytes(dep.Data.Signature)
if err != nil {
return err
}
sigs[i] = dsig
root, err := ssz.SigningRoot(dep.Data)
if err != nil {
return errors.Wrap(err, "could not get signing root")
}
signingData := &pb.SigningData{
ObjectRoot: root[:],
Domain: domain,
}
ctrRoot, err := ssz.HashTreeRoot(signingData)
if err != nil {
return errors.Wrap(err, "could not get container root")
}
msgs[i] = ctrRoot
}
verify, err := bls.VerifyMultipleSignatures(sigs, msgs, pks)
if err != nil {
return errors.Errorf("could not verify multiple signatures: %v", err)
}
if !verify {
return errors.New("one or more deposit signatures did not verify")
}
return nil
}

View File

@@ -0,0 +1,328 @@
package blocks_test
import (
"context"
"strings"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/trieutil"
)
func TestProcessDeposits_SameValidatorMultipleDepositsSameBlock(t *testing.T) {
// Same validator created 3 valid deposits within the same block
testutil.ResetCache()
dep, _, err := testutil.DeterministicDepositsAndKeysSameValidator(3)
if err != nil {
t.Fatal(err)
}
eth1Data, err := testutil.DeterministicEth1Data(len(dep))
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
// 3 deposits from the same validator
Deposits: []*ethpb.Deposit{dep[0], dep[1], dep[2]},
},
}
registry := []*ethpb.Validator{
{
PublicKey: []byte{1},
WithdrawalCredentials: []byte{1, 2, 3},
},
}
balances := []uint64{0}
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Balances: balances,
Eth1Data: eth1Data,
Fork: &pb.Fork{
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
CurrentVersion: params.BeaconConfig().GenesisForkVersion,
},
})
if err != nil {
t.Fatal(err)
}
newState, err := blocks.ProcessDeposits(context.Background(), beaconState, block.Body.Deposits)
if err != nil {
t.Fatalf("Expected block deposits to process correctly, received: %v", err)
}
if len(newState.Validators()) != 2 {
t.Errorf("Incorrect validator count. Wanted %d, got %d", 2, len(newState.Validators()))
}
}
func TestProcessDeposits_MerkleBranchFailsVerification(t *testing.T) {
deposit := &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: []byte{1, 2, 3},
Signature: make([]byte, 96),
},
}
leaf, err := ssz.HashTreeRoot(deposit.Data)
if err != nil {
t.Fatal(err)
}
// We then create a merkle branch for the test.
depositTrie, err := trieutil.GenerateTrieFromItems([][]byte{leaf[:]}, int(params.BeaconConfig().DepositContractTreeDepth))
if err != nil {
t.Fatalf("Could not generate trie: %v", err)
}
proof, err := depositTrie.MerkleProof(0)
if err != nil {
t.Fatalf("Could not generate proof: %v", err)
}
deposit.Proof = proof
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Deposits: []*ethpb.Deposit{deposit},
},
}
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Eth1Data: &ethpb.Eth1Data{
DepositRoot: []byte{0},
BlockHash: []byte{1},
},
})
if err != nil {
t.Fatal(err)
}
want := "deposit root did not verify"
_, err = blocks.ProcessDeposits(context.Background(), beaconState, block.Body.Deposits)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected error: %s, received %v", want, err)
}
}
func TestProcessDeposits_AddsNewValidatorDeposit(t *testing.T) {
dep, _, err := testutil.DeterministicDepositsAndKeys(1)
if err != nil {
t.Fatal(err)
}
eth1Data, err := testutil.DeterministicEth1Data(len(dep))
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Deposits: []*ethpb.Deposit{dep[0]},
},
}
registry := []*ethpb.Validator{
{
PublicKey: []byte{1},
WithdrawalCredentials: []byte{1, 2, 3},
},
}
balances := []uint64{0}
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Balances: balances,
Eth1Data: eth1Data,
Fork: &pb.Fork{
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
CurrentVersion: params.BeaconConfig().GenesisForkVersion,
},
})
if err != nil {
t.Fatal(err)
}
newState, err := blocks.ProcessDeposits(context.Background(), beaconState, block.Body.Deposits)
if err != nil {
t.Fatalf("Expected block deposits to process correctly, received: %v", err)
}
if newState.Balances()[1] != dep[0].Data.Amount {
t.Errorf(
"Expected state validator balances index 0 to equal %d, received %d",
dep[0].Data.Amount,
newState.Balances()[1],
)
}
}
func TestProcessDeposits_RepeatedDeposit_IncreasesValidatorBalance(t *testing.T) {
sk := bls.RandKey()
deposit := &ethpb.Deposit{
Data: &ethpb.Deposit_Data{
PublicKey: sk.PublicKey().Marshal(),
Amount: 1000,
},
}
sr, err := helpers.ComputeSigningRoot(deposit.Data, bytesutil.ToBytes(3, 8))
if err != nil {
t.Fatal(err)
}
sig := sk.Sign(sr[:])
deposit.Data.Signature = sig.Marshal()
leaf, err := ssz.HashTreeRoot(deposit.Data)
if err != nil {
t.Fatal(err)
}
// We then create a merkle branch for the test.
depositTrie, err := trieutil.GenerateTrieFromItems([][]byte{leaf[:]}, int(params.BeaconConfig().DepositContractTreeDepth))
if err != nil {
t.Fatalf("Could not generate trie: %v", err)
}
proof, err := depositTrie.MerkleProof(0)
if err != nil {
t.Fatalf("Could not generate proof: %v", err)
}
deposit.Proof = proof
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Deposits: []*ethpb.Deposit{deposit},
},
}
registry := []*ethpb.Validator{
{
PublicKey: []byte{1, 2, 3},
},
{
PublicKey: sk.PublicKey().Marshal(),
WithdrawalCredentials: []byte{1},
},
}
balances := []uint64{0, 50}
root := depositTrie.Root()
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Balances: balances,
Eth1Data: &ethpb.Eth1Data{
DepositRoot: root[:],
BlockHash: root[:],
},
})
if err != nil {
t.Fatal(err)
}
newState, err := blocks.ProcessDeposits(context.Background(), beaconState, block.Body.Deposits)
if err != nil {
t.Fatalf("Process deposit failed: %v", err)
}
if newState.Balances()[1] != 1000+50 {
t.Errorf("Expected balance at index 1 to be 1050, received %d", newState.Balances()[1])
}
}
func TestProcessDeposit_AddsNewValidatorDeposit(t *testing.T) {
//Similar to TestProcessDeposits_AddsNewValidatorDeposit except that this test directly calls ProcessDeposit
dep, _, err := testutil.DeterministicDepositsAndKeys(1)
if err != nil {
t.Fatal(err)
}
eth1Data, err := testutil.DeterministicEth1Data(len(dep))
if err != nil {
t.Fatal(err)
}
registry := []*ethpb.Validator{
{
PublicKey: []byte{1},
WithdrawalCredentials: []byte{1, 2, 3},
},
}
balances := []uint64{0}
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Balances: balances,
Eth1Data: eth1Data,
Fork: &pb.Fork{
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
CurrentVersion: params.BeaconConfig().GenesisForkVersion,
},
})
if err != nil {
t.Error(err)
}
newState, err := blocks.ProcessDeposit(beaconState, dep[0], true)
if err != nil {
t.Fatalf("Process deposit failed: %v", err)
}
if len(newState.Validators()) != 2 {
t.Errorf("Expected validator list to have length 2, received: %v", len(newState.Validators()))
}
if len(newState.Balances()) != 2 {
t.Fatalf("Expected validator balances list to have length 2, received: %v", len(newState.Balances()))
}
if newState.Balances()[1] != dep[0].Data.Amount {
t.Errorf(
"Expected state validator balances index 1 to equal %d, received %d",
dep[0].Data.Amount,
newState.Balances()[1],
)
}
}
func TestProcessDeposit_SkipsInvalidDeposit(t *testing.T) {
// Same test settings as in TestProcessDeposit_AddsNewValidatorDeposit, except that we use an invalid signature
dep, _, err := testutil.DeterministicDepositsAndKeys(1)
if err != nil {
t.Fatal(err)
}
dep[0].Data.Signature = make([]byte, 96)
trie, _, err := testutil.DepositTrieFromDeposits(dep)
if err != nil {
t.Fatal(err)
}
root := trie.Root()
eth1Data := &ethpb.Eth1Data{
DepositRoot: root[:],
DepositCount: 1,
}
registry := []*ethpb.Validator{
{
PublicKey: []byte{1},
WithdrawalCredentials: []byte{1, 2, 3},
},
}
balances := []uint64{0}
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Balances: balances,
Eth1Data: eth1Data,
Fork: &pb.Fork{
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
CurrentVersion: params.BeaconConfig().GenesisForkVersion,
},
})
if err != nil {
t.Fatal(err)
}
newState, err := blocks.ProcessDeposit(beaconState, dep[0], true)
if err != nil {
t.Fatalf("Expected invalid block deposit to be ignored without error, received: %v", err)
}
if newState.Eth1DepositIndex() != 1 {
t.Errorf(
"Expected Eth1DepositIndex to be increased by 1 after processing an invalid deposit, received change: %v",
newState.Eth1DepositIndex(),
)
}
if len(newState.Validators()) != 1 {
t.Errorf("Expected validator list to have length 1, received: %v", len(newState.Validators()))
}
if len(newState.Balances()) != 1 {
t.Errorf("Expected validator balances list to have length 1, received: %v", len(newState.Balances()))
}
if newState.Balances()[0] != 0 {
t.Errorf("Expected validator balance at index 0 to stay 0, received: %v", newState.Balances()[0])
}
}

View File

@@ -0,0 +1,74 @@
package blocks
import (
"bytes"
"errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/params"
)
// ProcessEth1DataInBlock is an operation performed on each
// beacon block to ensure the ETH1 data votes are processed
// into the beacon state.
//
// Official spec definition:
// def process_eth1_data(state: BeaconState, body: BeaconBlockBody) -> None:
// state.eth1_data_votes.append(body.eth1_data)
// if state.eth1_data_votes.count(body.eth1_data) * 2 > EPOCHS_PER_ETH1_VOTING_PERIOD * SLOTS_PER_EPOCH:
// state.latest_eth1_data = body.eth1_data
func ProcessEth1DataInBlock(beaconState *stateTrie.BeaconState, block *ethpb.BeaconBlock) (*stateTrie.BeaconState, error) {
if beaconState == nil {
return nil, errors.New("nil state")
}
if block == nil || block.Body == nil {
return nil, errors.New("nil block or block withought body")
}
if err := beaconState.AppendEth1DataVotes(block.Body.Eth1Data); err != nil {
return nil, err
}
hasSupport, err := Eth1DataHasEnoughSupport(beaconState, block.Body.Eth1Data)
if err != nil {
return nil, err
}
if hasSupport {
if err := beaconState.SetEth1Data(block.Body.Eth1Data); err != nil {
return nil, err
}
}
return beaconState, nil
}
// AreEth1DataEqual checks equality between two eth1 data objects.
func AreEth1DataEqual(a, b *ethpb.Eth1Data) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return a.DepositCount == b.DepositCount &&
bytes.Equal(a.BlockHash, b.BlockHash) &&
bytes.Equal(a.DepositRoot, b.DepositRoot)
}
// Eth1DataHasEnoughSupport returns true when the given eth1data has more than 50% votes in the
// eth1 voting period. A vote is cast by including eth1data in a block and part of state processing
// appends eth1data to the state in the Eth1DataVotes list. Iterating through this list checks the
// votes to see if they match the eth1data.
func Eth1DataHasEnoughSupport(beaconState *stateTrie.BeaconState, data *ethpb.Eth1Data) (bool, error) {
voteCount := uint64(0)
data = stateTrie.CopyETH1Data(data)
for _, vote := range beaconState.Eth1DataVotes() {
if AreEth1DataEqual(vote, data) {
voteCount++
}
}
// If 50+% majority converged on the same eth1data, then it has enough support to update the
// state.
support := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch
return voteCount*2 > support, nil
}

View File

@@ -4,6 +4,7 @@ import (
"fmt"
"testing"
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
beaconstate "github.com/prysmaticlabs/prysm/beacon-chain/state"
@@ -11,9 +12,9 @@ import (
"github.com/prysmaticlabs/prysm/shared/params"
)
func FakeDeposits(n int) []*ethpb.Eth1Data {
func FakeDeposits(n uint64) []*ethpb.Eth1Data {
deposits := make([]*ethpb.Eth1Data, n)
for i := 0; i < n; i++ {
for i := uint64(0); i < n; i++ {
deposits[i] = &ethpb.Eth1Data{
DepositCount: 1,
DepositRoot: []byte("root"),
@@ -30,7 +31,7 @@ func TestEth1DataHasEnoughSupport(t *testing.T) {
votingPeriodLength uint64
}{
{
stateVotes: FakeDeposits(4 * int(params.BeaconConfig().SlotsPerEpoch)),
stateVotes: FakeDeposits(4 * params.BeaconConfig().SlotsPerEpoch),
data: &ethpb.Eth1Data{
DepositCount: 1,
DepositRoot: []byte("root"),
@@ -38,7 +39,7 @@ func TestEth1DataHasEnoughSupport(t *testing.T) {
hasSupport: true,
votingPeriodLength: 7,
}, {
stateVotes: FakeDeposits(4 * int(params.BeaconConfig().SlotsPerEpoch)),
stateVotes: FakeDeposits(4 * params.BeaconConfig().SlotsPerEpoch),
data: &ethpb.Eth1Data{
DepositCount: 1,
DepositRoot: []byte("root"),
@@ -46,7 +47,7 @@ func TestEth1DataHasEnoughSupport(t *testing.T) {
hasSupport: false,
votingPeriodLength: 8,
}, {
stateVotes: FakeDeposits(4 * int(params.BeaconConfig().SlotsPerEpoch)),
stateVotes: FakeDeposits(4 * params.BeaconConfig().SlotsPerEpoch),
data: &ethpb.Eth1Data{
DepositCount: 1,
DepositRoot: []byte("root"),
@@ -56,6 +57,7 @@ func TestEth1DataHasEnoughSupport(t *testing.T) {
},
}
params.SetupTestConfigCleanup(t)
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
c := params.BeaconConfig()
@@ -84,3 +86,113 @@ func TestEth1DataHasEnoughSupport(t *testing.T) {
})
}
}
func TestAreEth1DataEqual(t *testing.T) {
type args struct {
a *ethpb.Eth1Data
b *ethpb.Eth1Data
}
tests := []struct {
name string
args args
want bool
}{
{
name: "true when both are nil",
args: args{
a: nil,
b: nil,
},
want: true,
},
{
name: "false when only one is nil",
args: args{
a: nil,
b: &ethpb.Eth1Data{
DepositRoot: make([]byte, 32),
DepositCount: 0,
BlockHash: make([]byte, 32),
},
},
want: false,
},
{
name: "true when real equality",
args: args{
a: &ethpb.Eth1Data{
DepositRoot: make([]byte, 32),
DepositCount: 0,
BlockHash: make([]byte, 32),
},
b: &ethpb.Eth1Data{
DepositRoot: make([]byte, 32),
DepositCount: 0,
BlockHash: make([]byte, 32),
},
},
want: true,
},
{
name: "false is field value differs",
args: args{
a: &ethpb.Eth1Data{
DepositRoot: make([]byte, 32),
DepositCount: 0,
BlockHash: make([]byte, 32),
},
b: &ethpb.Eth1Data{
DepositRoot: make([]byte, 32),
DepositCount: 64,
BlockHash: make([]byte, 32),
},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := blocks.AreEth1DataEqual(tt.args.a, tt.args.b); got != tt.want {
t.Errorf("AreEth1DataEqual() = %v, want %v", got, tt.want)
}
})
}
}
func TestProcessEth1Data_SetsCorrectly(t *testing.T) {
beaconState, err := beaconstate.InitializeFromProto(&pb.BeaconState{
Eth1DataVotes: []*ethpb.Eth1Data{},
})
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
Eth1Data: &ethpb.Eth1Data{
DepositRoot: []byte{2},
BlockHash: []byte{3},
},
},
}
period := params.BeaconConfig().EpochsPerEth1VotingPeriod * params.BeaconConfig().SlotsPerEpoch
for i := uint64(0); i < period; i++ {
beaconState, err = blocks.ProcessEth1DataInBlock(beaconState, block)
if err != nil {
t.Fatal(err)
}
}
newETH1DataVotes := beaconState.Eth1DataVotes()
if len(newETH1DataVotes) <= 1 {
t.Error("Expected new ETH1 data votes to have length > 1")
}
if !proto.Equal(beaconState.Eth1Data(), beaconstate.CopyETH1Data(block.Body.Eth1Data)) {
t.Errorf(
"Expected latest eth1 data to have been set to %v, received %v",
block.Body.Eth1Data,
beaconState.Eth1Data(),
)
}
}

View File

@@ -0,0 +1,140 @@
package blocks
import (
"context"
"fmt"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/params"
)
// ProcessVoluntaryExits is one of the operations performed
// on each processed beacon block to determine which validators
// should exit the state's validator registry.
//
// Spec pseudocode definition:
// def process_voluntary_exit(state: BeaconState, exit: VoluntaryExit) -> None:
// """
// Process ``VoluntaryExit`` operation.
// """
// validator = state.validator_registry[exit.validator_index]
// # Verify the validator is active
// assert is_active_validator(validator, get_current_epoch(state))
// # Verify the validator has not yet exited
// assert validator.exit_epoch == FAR_FUTURE_EPOCH
// # Exits must specify an epoch when they become valid; they are not valid before then
// assert get_current_epoch(state) >= exit.epoch
// # Verify the validator has been active long enough
// assert get_current_epoch(state) >= validator.activation_epoch + PERSISTENT_COMMITTEE_PERIOD
// # Verify signature
// domain = get_domain(state, DOMAIN_VOLUNTARY_EXIT, exit.epoch)
// assert bls_verify(validator.pubkey, signing_root(exit), exit.signature, domain)
// # Initiate exit
// initiate_validator_exit(state, exit.validator_index)
func ProcessVoluntaryExits(
ctx context.Context,
beaconState *stateTrie.BeaconState,
body *ethpb.BeaconBlockBody,
) (*stateTrie.BeaconState, error) {
exits := body.VoluntaryExits
for idx, exit := range exits {
if exit == nil || exit.Exit == nil {
return nil, errors.New("nil voluntary exit in block body")
}
val, err := beaconState.ValidatorAtIndexReadOnly(exit.Exit.ValidatorIndex)
if err != nil {
return nil, err
}
if err := VerifyExit(val, beaconState.Slot(), beaconState.Fork(), exit, beaconState.GenesisValidatorRoot()); err != nil {
return nil, errors.Wrapf(err, "could not verify exit %d", idx)
}
beaconState, err = v.InitiateValidatorExit(beaconState, exit.Exit.ValidatorIndex)
if err != nil {
return nil, err
}
}
return beaconState, nil
}
// ProcessVoluntaryExitsNoVerify processes all the voluntary exits in
// a block body, without verifying their BLS signatures.
func ProcessVoluntaryExitsNoVerify(
beaconState *stateTrie.BeaconState,
body *ethpb.BeaconBlockBody,
) (*stateTrie.BeaconState, error) {
var err error
exits := body.VoluntaryExits
for idx, exit := range exits {
if exit == nil || exit.Exit == nil {
return nil, errors.New("nil exit")
}
beaconState, err = v.InitiateValidatorExit(beaconState, exit.Exit.ValidatorIndex)
if err != nil {
return nil, errors.Wrapf(err, "failed to process voluntary exit at index %d", idx)
}
}
return beaconState, nil
}
// VerifyExit implements the spec defined validation for voluntary exits.
//
// Spec pseudocode definition:
// def process_voluntary_exit(state: BeaconState, exit: VoluntaryExit) -> None:
// """
// Process ``VoluntaryExit`` operation.
// """
// validator = state.validator_registry[exit.validator_index]
// # Verify the validator is active
// assert is_active_validator(validator, get_current_epoch(state))
// # Verify the validator has not yet exited
// assert validator.exit_epoch == FAR_FUTURE_EPOCH
// # Exits must specify an epoch when they become valid; they are not valid before then
// assert get_current_epoch(state) >= exit.epoch
// # Verify the validator has been active long enough
// assert get_current_epoch(state) >= validator.activation_epoch + PERSISTENT_COMMITTEE_PERIOD
// # Verify signature
// domain = get_domain(state, DOMAIN_VOLUNTARY_EXIT, exit.epoch)
// assert bls_verify(validator.pubkey, signing_root(exit), exit.signature, domain)
func VerifyExit(validator *stateTrie.ReadOnlyValidator, currentSlot uint64, fork *pb.Fork, signed *ethpb.SignedVoluntaryExit, genesisRoot []byte) error {
if signed == nil || signed.Exit == nil {
return errors.New("nil exit")
}
exit := signed.Exit
currentEpoch := helpers.SlotToEpoch(currentSlot)
// Verify the validator is active.
if !helpers.IsActiveValidatorUsingTrie(validator, currentEpoch) {
return errors.New("non-active validator cannot exit")
}
// Verify the validator has not yet exited.
if validator.ExitEpoch() != params.BeaconConfig().FarFutureEpoch {
return fmt.Errorf("validator has already exited at epoch: %v", validator.ExitEpoch())
}
// Exits must specify an epoch when they become valid; they are not valid before then.
if currentEpoch < exit.Epoch {
return fmt.Errorf("expected current epoch >= exit epoch, received %d < %d", currentEpoch, exit.Epoch)
}
// Verify the validator has been active long enough.
if currentEpoch < validator.ActivationEpoch()+params.BeaconConfig().ShardCommitteePeriod {
return fmt.Errorf(
"validator has not been active long enough to exit, wanted epoch %d >= %d",
currentEpoch,
validator.ActivationEpoch()+params.BeaconConfig().ShardCommitteePeriod,
)
}
domain, err := helpers.Domain(fork, exit.Epoch, params.BeaconConfig().DomainVoluntaryExit, genesisRoot)
if err != nil {
return err
}
valPubKey := validator.PublicKey()
if err := helpers.VerifySigningRoot(exit, valPubKey[:], signed.Signature, domain); err != nil {
return helpers.ErrSigFailedToVerify
}
return nil
}

View File

@@ -0,0 +1,177 @@
package blocks_test
import (
"context"
"strings"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestProcessVoluntaryExits_ValidatorNotActive(t *testing.T) {
exits := []*ethpb.SignedVoluntaryExit{
{
Exit: &ethpb.VoluntaryExit{
ValidatorIndex: 0,
},
},
}
registry := []*ethpb.Validator{
{
ExitEpoch: 0,
},
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
})
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
VoluntaryExits: exits,
},
}
want := "non-active validator cannot exit"
_, err = blocks.ProcessVoluntaryExits(context.Background(), state, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessVoluntaryExits_InvalidExitEpoch(t *testing.T) {
exits := []*ethpb.SignedVoluntaryExit{
{
Exit: &ethpb.VoluntaryExit{
Epoch: 10,
},
},
}
registry := []*ethpb.Validator{
{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
},
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Slot: 0,
})
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
VoluntaryExits: exits,
},
}
want := "expected current epoch >= exit epoch"
_, err = blocks.ProcessVoluntaryExits(context.Background(), state, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessVoluntaryExits_NotActiveLongEnoughToExit(t *testing.T) {
exits := []*ethpb.SignedVoluntaryExit{
{
Exit: &ethpb.VoluntaryExit{
ValidatorIndex: 0,
Epoch: 0,
},
},
}
registry := []*ethpb.Validator{
{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
},
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Slot: 10,
})
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
VoluntaryExits: exits,
},
}
want := "validator has not been active long enough to exit"
_, err = blocks.ProcessVoluntaryExits(context.Background(), state, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessVoluntaryExits_AppliesCorrectStatus(t *testing.T) {
exits := []*ethpb.SignedVoluntaryExit{
{
Exit: &ethpb.VoluntaryExit{
ValidatorIndex: 0,
Epoch: 0,
},
},
}
registry := []*ethpb.Validator{
{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
ActivationEpoch: 0,
},
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Fork: &pb.Fork{
CurrentVersion: params.BeaconConfig().GenesisForkVersion,
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
},
Slot: params.BeaconConfig().SlotsPerEpoch * 5,
})
if err != nil {
t.Fatal(err)
}
err = state.SetSlot(state.Slot() + (params.BeaconConfig().ShardCommitteePeriod * params.BeaconConfig().SlotsPerEpoch))
if err != nil {
t.Fatal(err)
}
priv := bls.RandKey()
val, err := state.ValidatorAtIndex(0)
if err != nil {
t.Fatal(err)
}
val.PublicKey = priv.PublicKey().Marshal()[:]
if err := state.UpdateValidatorAtIndex(0, val); err != nil {
t.Fatal(err)
}
exits[0].Signature, err = helpers.ComputeDomainAndSign(state, helpers.CurrentEpoch(state), exits[0].Exit, params.BeaconConfig().DomainVoluntaryExit, priv)
require.NoError(t, err)
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
VoluntaryExits: exits,
},
}
newState, err := blocks.ProcessVoluntaryExits(context.Background(), state, block.Body)
if err != nil {
t.Fatalf("Could not process exits: %v", err)
}
newRegistry := newState.Validators()
if newRegistry[0].ExitEpoch != helpers.ActivationExitEpoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch) {
t.Errorf("Expected validator exit epoch to be %d, got %d",
helpers.ActivationExitEpoch(state.Slot()/params.BeaconConfig().SlotsPerEpoch), newRegistry[0].ExitEpoch)
}
}

View File

@@ -1,6 +1,5 @@
// Package blocks contains block processing libraries. These libraries
// process and verify block specific messages such as PoW receipt root,
// RANDAO, validator deposits, exits and slashing proofs.
// Package blocks contains block processing libraries according to
// the eth2spec.
package blocks
import (

View File

@@ -0,0 +1,135 @@
package blocks
import (
"bytes"
"fmt"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
"github.com/prysmaticlabs/prysm/shared/params"
)
// ProcessBlockHeader validates a block by its header.
//
// Spec pseudocode definition:
//
// def process_block_header(state: BeaconState, block: BeaconBlock) -> None:
// # Verify that the slots match
// assert block.slot == state.slot
// # Verify that proposer index is the correct index
// assert block.proposer_index == get_beacon_proposer_index(state)
// # Verify that the parent matches
// assert block.parent_root == hash_tree_root(state.latest_block_header)
// # Save current block as the new latest block
// state.latest_block_header = BeaconBlockHeader(
// slot=block.slot,
// parent_root=block.parent_root,
// # state_root: zeroed, overwritten in the next `process_slot` call
// body_root=hash_tree_root(block.body),
// # signature is always zeroed
// )
// # Verify proposer is not slashed
// proposer = state.validators[get_beacon_proposer_index(state)]
// assert not proposer.slashed
// # Verify proposer signature
// assert bls_verify(proposer.pubkey, signing_root(block), block.signature, get_domain(state, DOMAIN_BEACON_PROPOSER))
func ProcessBlockHeader(
beaconState *stateTrie.BeaconState,
block *ethpb.SignedBeaconBlock,
) (*stateTrie.BeaconState, error) {
beaconState, err := ProcessBlockHeaderNoVerify(beaconState, block.Block)
if err != nil {
return nil, err
}
// Verify proposer signature.
if err := VerifyBlockSignature(beaconState, block); err != nil {
return nil, err
}
return beaconState, nil
}
// ProcessBlockHeaderNoVerify validates a block by its header but skips proposer
// signature verification.
//
// WARNING: This method does not verify proposer signature. This is used for proposer to compute state root
// using a unsigned block.
//
// Spec pseudocode definition:
// def process_block_header(state: BeaconState, block: BeaconBlock) -> None:
// # Verify that the slots match
// assert block.slot == state.slot
// # Verify that proposer index is the correct index
// assert block.proposer_index == get_beacon_proposer_index(state)
// # Verify that the parent matches
// assert block.parent_root == hash_tree_root(state.latest_block_header)
// # Save current block as the new latest block
// state.latest_block_header = BeaconBlockHeader(
// slot=block.slot,
// parent_root=block.parent_root,
// # state_root: zeroed, overwritten in the next `process_slot` call
// body_root=hash_tree_root(block.body),
// # signature is always zeroed
// )
// # Verify proposer is not slashed
// proposer = state.validators[get_beacon_proposer_index(state)]
// assert not proposer.slashed
func ProcessBlockHeaderNoVerify(
beaconState *stateTrie.BeaconState,
block *ethpb.BeaconBlock,
) (*stateTrie.BeaconState, error) {
if block == nil {
return nil, errors.New("nil block")
}
if beaconState.Slot() != block.Slot {
return nil, fmt.Errorf("state slot: %d is different than block slot: %d", beaconState.Slot(), block.Slot)
}
idx, err := helpers.BeaconProposerIndex(beaconState)
if err != nil {
return nil, err
}
if block.ProposerIndex != idx {
return nil, fmt.Errorf("proposer index: %d is different than calculated: %d", block.ProposerIndex, idx)
}
parentHeader := beaconState.LatestBlockHeader()
if parentHeader.Slot >= block.Slot {
return nil, fmt.Errorf("block.Slot %d must be greater than state.LatestBlockHeader.Slot %d", block.Slot, parentHeader.Slot)
}
parentRoot, err := stateutil.BlockHeaderRoot(parentHeader)
if err != nil {
return nil, err
}
if !bytes.Equal(block.ParentRoot, parentRoot[:]) {
return nil, fmt.Errorf(
"parent root %#x does not match the latest block header signing root in state %#x",
block.ParentRoot, parentRoot)
}
proposer, err := beaconState.ValidatorAtIndexReadOnly(idx)
if err != nil {
return nil, err
}
if proposer.Slashed() {
return nil, fmt.Errorf("proposer at index %d was previously slashed", idx)
}
bodyRoot, err := stateutil.BlockBodyRoot(block.Body)
if err != nil {
return nil, err
}
if err := beaconState.SetLatestBlockHeader(&ethpb.BeaconBlockHeader{
Slot: block.Slot,
ProposerIndex: block.ProposerIndex,
ParentRoot: block.ParentRoot,
StateRoot: params.BeaconConfig().ZeroHash[:],
BodyRoot: bodyRoot[:],
}); err != nil {
return nil, err
}
return beaconState, nil
}

View File

@@ -0,0 +1,437 @@
package blocks_test
import (
"io/ioutil"
"strings"
"testing"
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/sirupsen/logrus"
)
func init() {
logrus.SetOutput(ioutil.Discard) // Ignore "validator activated" logs
}
func TestProcessBlockHeader_ImproperBlockSlot(t *testing.T) {
validators := make([]*ethpb.Validator, params.BeaconConfig().MinGenesisActiveValidatorCount)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
Slashed: true,
}
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: validators,
Slot: 10,
LatestBlockHeader: &ethpb.BeaconBlockHeader{Slot: 10}, // Must be less than block.Slot
Fork: &pb.Fork{
PreviousVersion: []byte{0, 0, 0, 0},
CurrentVersion: []byte{0, 0, 0, 0},
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
if err != nil {
t.Fatal(err)
}
latestBlockSignedRoot, err := stateutil.BlockHeaderRoot(state.LatestBlockHeader())
if err != nil {
t.Error(err)
}
currentEpoch := helpers.CurrentEpoch(state)
priv := bls.RandKey()
pID, err := helpers.BeaconProposerIndex(state)
if err != nil {
t.Error(err)
}
block := &ethpb.SignedBeaconBlock{
Block: &ethpb.BeaconBlock{
ProposerIndex: pID,
Slot: 10,
Body: &ethpb.BeaconBlockBody{
RandaoReveal: []byte{'A', 'B', 'C'},
},
ParentRoot: latestBlockSignedRoot[:],
},
}
block.Signature, err = helpers.ComputeDomainAndSign(state, currentEpoch, block.Block, params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(state)
if err != nil {
t.Fatal(err)
}
validators[proposerIdx].Slashed = false
validators[proposerIdx].PublicKey = priv.PublicKey().Marshal()
err = state.UpdateValidatorAtIndex(proposerIdx, validators[proposerIdx])
if err != nil {
t.Fatal(err)
}
_, err = blocks.ProcessBlockHeader(state, block)
if err == nil || err.Error() != "block.Slot 10 must be greater than state.LatestBlockHeader.Slot 10" {
t.Fatalf("did not get expected error, got %v", err)
}
}
func TestProcessBlockHeader_WrongProposerSig(t *testing.T) {
testutil.ResetCache()
beaconState, privKeys := testutil.DeterministicGenesisState(t, 100)
if err := beaconState.SetLatestBlockHeader(&ethpb.BeaconBlockHeader{Slot: 9}); err != nil {
t.Fatal(err)
}
if err := beaconState.SetSlot(10); err != nil {
t.Error(err)
}
lbhdr, err := stateutil.BlockHeaderRoot(beaconState.LatestBlockHeader())
if err != nil {
t.Error(err)
}
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
if err != nil {
t.Error(err)
}
block := &ethpb.SignedBeaconBlock{
Block: &ethpb.BeaconBlock{
ProposerIndex: proposerIdx,
Slot: 10,
Body: &ethpb.BeaconBlockBody{
RandaoReveal: []byte{'A', 'B', 'C'},
},
ParentRoot: lbhdr[:],
},
}
block.Signature, err = helpers.ComputeDomainAndSign(beaconState, 0, block.Block, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx+1])
require.NoError(t, err)
_, err = blocks.ProcessBlockHeader(beaconState, block)
want := "signature did not verify"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %v, received %v", want, err)
}
}
func TestProcessBlockHeader_DifferentSlots(t *testing.T) {
validators := make([]*ethpb.Validator, params.BeaconConfig().MinGenesisActiveValidatorCount)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
Slashed: true,
}
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: validators,
Slot: 10,
LatestBlockHeader: &ethpb.BeaconBlockHeader{Slot: 9},
Fork: &pb.Fork{
PreviousVersion: []byte{0, 0, 0, 0},
CurrentVersion: []byte{0, 0, 0, 0},
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
if err != nil {
t.Fatal(err)
}
lbhsr, err := ssz.HashTreeRoot(state.LatestBlockHeader())
if err != nil {
t.Error(err)
}
currentEpoch := helpers.CurrentEpoch(state)
priv := bls.RandKey()
blockSig, err := helpers.ComputeDomainAndSign(state, currentEpoch, []byte("hello"), params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
validators[5896].PublicKey = priv.PublicKey().Marshal()
block := &ethpb.SignedBeaconBlock{
Block: &ethpb.BeaconBlock{
Slot: 1,
Body: &ethpb.BeaconBlockBody{
RandaoReveal: []byte{'A', 'B', 'C'},
},
ParentRoot: lbhsr[:],
},
Signature: blockSig,
}
_, err = blocks.ProcessBlockHeader(state, block)
want := "is different than block slot"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %v, received %v", want, err)
}
}
func TestProcessBlockHeader_PreviousBlockRootNotSignedRoot(t *testing.T) {
validators := make([]*ethpb.Validator, params.BeaconConfig().MinGenesisActiveValidatorCount)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
Slashed: true,
}
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: validators,
Slot: 10,
LatestBlockHeader: &ethpb.BeaconBlockHeader{Slot: 9},
Fork: &pb.Fork{
PreviousVersion: []byte{0, 0, 0, 0},
CurrentVersion: []byte{0, 0, 0, 0},
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
if err != nil {
t.Fatal(err)
}
currentEpoch := helpers.CurrentEpoch(state)
priv := bls.RandKey()
blockSig, err := helpers.ComputeDomainAndSign(state, currentEpoch, []byte("hello"), params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
validators[5896].PublicKey = priv.PublicKey().Marshal()
pID, err := helpers.BeaconProposerIndex(state)
if err != nil {
t.Error(err)
}
block := &ethpb.SignedBeaconBlock{
Block: &ethpb.BeaconBlock{
ProposerIndex: pID,
Slot: 10,
Body: &ethpb.BeaconBlockBody{
RandaoReveal: []byte{'A', 'B', 'C'},
},
ParentRoot: []byte{'A'},
},
Signature: blockSig,
}
_, err = blocks.ProcessBlockHeader(state, block)
want := "does not match"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %v, received %v", want, err)
}
}
func TestProcessBlockHeader_SlashedProposer(t *testing.T) {
validators := make([]*ethpb.Validator, params.BeaconConfig().MinGenesisActiveValidatorCount)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
Slashed: true,
}
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: validators,
Slot: 10,
LatestBlockHeader: &ethpb.BeaconBlockHeader{Slot: 9},
Fork: &pb.Fork{
PreviousVersion: []byte{0, 0, 0, 0},
CurrentVersion: []byte{0, 0, 0, 0},
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
if err != nil {
t.Fatal(err)
}
parentRoot, err := stateutil.BlockHeaderRoot(state.LatestBlockHeader())
if err != nil {
t.Error(err)
}
currentEpoch := helpers.CurrentEpoch(state)
priv := bls.RandKey()
blockSig, err := helpers.ComputeDomainAndSign(state, currentEpoch, []byte("hello"), params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
validators[12683].PublicKey = priv.PublicKey().Marshal()
pID, err := helpers.BeaconProposerIndex(state)
if err != nil {
t.Error(err)
}
block := &ethpb.SignedBeaconBlock{
Block: &ethpb.BeaconBlock{
ProposerIndex: pID,
Slot: 10,
Body: &ethpb.BeaconBlockBody{
RandaoReveal: []byte{'A', 'B', 'C'},
},
ParentRoot: parentRoot[:],
},
Signature: blockSig,
}
_, err = blocks.ProcessBlockHeader(state, block)
want := "was previously slashed"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %v, received %v", want, err)
}
}
func TestProcessBlockHeader_OK(t *testing.T) {
validators := make([]*ethpb.Validator, params.BeaconConfig().MinGenesisActiveValidatorCount)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
Slashed: true,
}
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: validators,
Slot: 10,
LatestBlockHeader: &ethpb.BeaconBlockHeader{Slot: 9},
Fork: &pb.Fork{
PreviousVersion: []byte{0, 0, 0, 0},
CurrentVersion: []byte{0, 0, 0, 0},
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
if err != nil {
t.Fatal(err)
}
latestBlockSignedRoot, err := stateutil.BlockHeaderRoot(state.LatestBlockHeader())
if err != nil {
t.Error(err)
}
currentEpoch := helpers.CurrentEpoch(state)
priv := bls.RandKey()
pID, err := helpers.BeaconProposerIndex(state)
if err != nil {
t.Error(err)
}
block := &ethpb.SignedBeaconBlock{
Block: &ethpb.BeaconBlock{
ProposerIndex: pID,
Slot: 10,
Body: &ethpb.BeaconBlockBody{
RandaoReveal: []byte{'A', 'B', 'C'},
},
ParentRoot: latestBlockSignedRoot[:],
},
}
block.Signature, err = helpers.ComputeDomainAndSign(state, currentEpoch, block.Block, params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
bodyRoot, err := stateutil.BlockBodyRoot(block.Block.Body)
if err != nil {
t.Fatalf("Failed to hash block bytes got: %v", err)
}
proposerIdx, err := helpers.BeaconProposerIndex(state)
if err != nil {
t.Fatal(err)
}
validators[proposerIdx].Slashed = false
validators[proposerIdx].PublicKey = priv.PublicKey().Marshal()
err = state.UpdateValidatorAtIndex(proposerIdx, validators[proposerIdx])
if err != nil {
t.Fatal(err)
}
newState, err := blocks.ProcessBlockHeader(state, block)
if err != nil {
t.Fatalf("Failed to process block header got: %v", err)
}
var zeroHash [32]byte
nsh := newState.LatestBlockHeader()
expected := &ethpb.BeaconBlockHeader{
ProposerIndex: pID,
Slot: block.Block.Slot,
ParentRoot: latestBlockSignedRoot[:],
BodyRoot: bodyRoot[:],
StateRoot: zeroHash[:],
}
if !proto.Equal(nsh, expected) {
t.Errorf("Expected %v, received %v", expected, nsh)
}
}
func TestBlockSignatureSet_OK(t *testing.T) {
validators := make([]*ethpb.Validator, params.BeaconConfig().MinGenesisActiveValidatorCount)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
Slashed: true,
}
}
state, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: validators,
Slot: 10,
LatestBlockHeader: &ethpb.BeaconBlockHeader{Slot: 9},
Fork: &pb.Fork{
PreviousVersion: []byte{0, 0, 0, 0},
CurrentVersion: []byte{0, 0, 0, 0},
},
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
if err != nil {
t.Fatal(err)
}
latestBlockSignedRoot, err := stateutil.BlockHeaderRoot(state.LatestBlockHeader())
if err != nil {
t.Error(err)
}
currentEpoch := helpers.CurrentEpoch(state)
priv := bls.RandKey()
pID, err := helpers.BeaconProposerIndex(state)
if err != nil {
t.Error(err)
}
block := &ethpb.SignedBeaconBlock{
Block: &ethpb.BeaconBlock{
ProposerIndex: pID,
Slot: 10,
Body: &ethpb.BeaconBlockBody{
RandaoReveal: []byte{'A', 'B', 'C'},
},
ParentRoot: latestBlockSignedRoot[:],
},
}
block.Signature, err = helpers.ComputeDomainAndSign(state, currentEpoch, block.Block, params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(state)
if err != nil {
t.Fatal(err)
}
validators[proposerIdx].Slashed = false
validators[proposerIdx].PublicKey = priv.PublicKey().Marshal()
err = state.UpdateValidatorAtIndex(proposerIdx, validators[proposerIdx])
if err != nil {
t.Fatal(err)
}
set, err := blocks.BlockSignatureSet(state, block)
if err != nil {
t.Fatal(err)
}
verified, err := set.Verify()
if err != nil {
t.Fatal(err)
}
if !verified {
t.Error("Block signature set returned a set which was unable to be verified")
}
}

View File

@@ -0,0 +1,5 @@
package blocks
import "github.com/sirupsen/logrus"
var log = logrus.WithField("prefix", "blocks")

View File

@@ -0,0 +1,96 @@
package blocks
import (
"context"
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/params"
)
// ProcessProposerSlashings is one of the operations performed
// on each processed beacon block to slash proposers based on
// slashing conditions if any slashable events occurred.
//
// Spec pseudocode definition:
// def process_proposer_slashing(state: BeaconState, proposer_slashing: ProposerSlashing) -> None:
// """
// Process ``ProposerSlashing`` operation.
// """
// proposer = state.validator_registry[proposer_slashing.proposer_index]
// # Verify slots match
// assert proposer_slashing.header_1.slot == proposer_slashing.header_2.slot
// # But the headers are different
// assert proposer_slashing.header_1 != proposer_slashing.header_2
// # Check proposer is slashable
// assert is_slashable_validator(proposer, get_current_epoch(state))
// # Signatures are valid
// for header in (proposer_slashing.header_1, proposer_slashing.header_2):
// domain = get_domain(state, DOMAIN_BEACON_PROPOSER, slot_to_epoch(header.slot))
// assert bls_verify(proposer.pubkey, signing_root(header), header.signature, domain)
//
// slash_validator(state, proposer_slashing.proposer_index)
func ProcessProposerSlashings(
ctx context.Context,
beaconState *stateTrie.BeaconState,
body *ethpb.BeaconBlockBody,
) (*stateTrie.BeaconState, error) {
var err error
for idx, slashing := range body.ProposerSlashings {
if slashing == nil {
return nil, errors.New("nil proposer slashings in block body")
}
if err = VerifyProposerSlashing(beaconState, slashing); err != nil {
return nil, errors.Wrapf(err, "could not verify proposer slashing %d", idx)
}
beaconState, err = v.SlashValidator(
beaconState, slashing.Header_1.Header.ProposerIndex,
)
if err != nil {
return nil, errors.Wrapf(err, "could not slash proposer index %d", slashing.Header_1.Header.ProposerIndex)
}
}
return beaconState, nil
}
// VerifyProposerSlashing verifies that the data provided from slashing is valid.
func VerifyProposerSlashing(
beaconState *stateTrie.BeaconState,
slashing *ethpb.ProposerSlashing,
) error {
if slashing.Header_1 == nil || slashing.Header_1.Header == nil || slashing.Header_2 == nil || slashing.Header_2.Header == nil {
return errors.New("nil header cannot be verified")
}
hSlot := slashing.Header_1.Header.Slot
if hSlot != slashing.Header_2.Header.Slot {
return fmt.Errorf("mismatched header slots, received %d == %d", slashing.Header_1.Header.Slot, slashing.Header_2.Header.Slot)
}
pIdx := slashing.Header_1.Header.ProposerIndex
if pIdx != slashing.Header_2.Header.ProposerIndex {
return fmt.Errorf("mismatched indices, received %d == %d", slashing.Header_1.Header.ProposerIndex, slashing.Header_2.Header.ProposerIndex)
}
if proto.Equal(slashing.Header_1, slashing.Header_2) {
return errors.New("expected slashing headers to differ")
}
proposer, err := beaconState.ValidatorAtIndexReadOnly(slashing.Header_1.Header.ProposerIndex)
if err != nil {
return err
}
if !helpers.IsSlashableValidatorUsingTrie(proposer, helpers.SlotToEpoch(beaconState.Slot())) {
return fmt.Errorf("validator with key %#x is not slashable", proposer.PublicKey())
}
headers := []*ethpb.SignedBeaconBlockHeader{slashing.Header_1, slashing.Header_2}
for _, header := range headers {
if err := helpers.ComputeDomainVerifySigningRoot(beaconState, pIdx, helpers.SlotToEpoch(hSlot),
header.Header, params.BeaconConfig().DomainBeaconProposer, header.Signature); err != nil {
return errors.Wrap(err, "could not verify beacon block header")
}
}
return nil
}

View File

@@ -0,0 +1,194 @@
package blocks_test
import (
"context"
"fmt"
"strings"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestProcessProposerSlashings_UnmatchedHeaderSlots(t *testing.T) {
testutil.ResetCache()
beaconState, _ := testutil.DeterministicGenesisState(t, 20)
currentSlot := uint64(0)
slashings := []*ethpb.ProposerSlashing{
{
Header_1: &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{
ProposerIndex: 1,
Slot: params.BeaconConfig().SlotsPerEpoch + 1,
},
},
Header_2: &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{
ProposerIndex: 1,
Slot: 0,
},
},
},
}
if err := beaconState.SetSlot(currentSlot); err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
ProposerSlashings: slashings,
},
}
want := "mismatched header slots"
_, err := blocks.ProcessProposerSlashings(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessProposerSlashings_SameHeaders(t *testing.T) {
testutil.ResetCache()
beaconState, _ := testutil.DeterministicGenesisState(t, 2)
currentSlot := uint64(0)
slashings := []*ethpb.ProposerSlashing{
{
Header_1: &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{
ProposerIndex: 1,
Slot: 0,
},
},
Header_2: &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{
ProposerIndex: 1,
Slot: 0,
},
},
},
}
if err := beaconState.SetSlot(currentSlot); err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
ProposerSlashings: slashings,
},
}
want := "expected slashing headers to differ"
_, err := blocks.ProcessProposerSlashings(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessProposerSlashings_ValidatorNotSlashable(t *testing.T) {
registry := []*ethpb.Validator{
{
PublicKey: []byte("key"),
Slashed: true,
ActivationEpoch: 0,
WithdrawableEpoch: 0,
},
}
currentSlot := uint64(0)
slashings := []*ethpb.ProposerSlashing{
{
Header_1: &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{
ProposerIndex: 0,
Slot: 0,
},
Signature: []byte("A"),
},
Header_2: &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{
ProposerIndex: 0,
Slot: 0,
},
Signature: []byte("B"),
},
},
}
beaconState, err := stateTrie.InitializeFromProto(&pb.BeaconState{
Validators: registry,
Slot: currentSlot,
})
if err != nil {
t.Fatal(err)
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
ProposerSlashings: slashings,
},
}
want := fmt.Sprintf(
"validator with key %#x is not slashable",
bytesutil.ToBytes48(beaconState.Validators()[0].PublicKey),
)
_, err = blocks.ProcessProposerSlashings(context.Background(), beaconState, block.Body)
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("Expected %s, received %v", want, err)
}
}
func TestProcessProposerSlashings_AppliesCorrectStatus(t *testing.T) {
// We test the case when data is correct and verify the validator
// registry has been updated.
beaconState, privKeys := testutil.DeterministicGenesisState(t, 100)
proposerIdx := uint64(1)
header1 := &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{
ProposerIndex: proposerIdx,
Slot: 0,
StateRoot: []byte("A"),
},
}
var err error
header1.Signature, err = helpers.ComputeDomainAndSign(beaconState, 0, header1.Header, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx])
require.NoError(t, err)
header2 := &ethpb.SignedBeaconBlockHeader{
Header: &ethpb.BeaconBlockHeader{
ProposerIndex: proposerIdx,
Slot: 0,
StateRoot: []byte("B"),
},
}
header2.Signature, err = helpers.ComputeDomainAndSign(beaconState, 0, header2.Header, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx])
require.NoError(t, err)
slashings := []*ethpb.ProposerSlashing{
{
Header_1: header1,
Header_2: header2,
},
}
block := &ethpb.BeaconBlock{
Body: &ethpb.BeaconBlockBody{
ProposerSlashings: slashings,
},
}
newState, err := blocks.ProcessProposerSlashings(context.Background(), beaconState, block.Body)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
newStateVals := newState.Validators()
if newStateVals[1].ExitEpoch != beaconState.Validators()[1].ExitEpoch {
t.Errorf("Proposer with index 1 did not correctly exit,"+"wanted slot:%d, got:%d",
newStateVals[1].ExitEpoch, beaconState.Validators()[1].ExitEpoch)
}
}

View File

@@ -0,0 +1,77 @@
package blocks
import (
"github.com/pkg/errors"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
stateTrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/hashutil"
"github.com/prysmaticlabs/prysm/shared/params"
)
// ProcessRandao checks the block proposer's
// randao commitment and generates a new randao mix to update
// in the beacon state's latest randao mixes slice.
//
// Spec pseudocode definition:
// def process_randao(state: BeaconState, body: BeaconBlockBody) -> None:
// epoch = get_current_epoch(state)
// # Verify RANDAO reveal
// proposer = state.validators[get_beacon_proposer_index(state)]
// signing_root = compute_signing_root(epoch, get_domain(state, DOMAIN_RANDAO))
// assert bls.Verify(proposer.pubkey, signing_root, body.randao_reveal)
// # Mix in RANDAO reveal
// mix = xor(get_randao_mix(state, epoch), hash(body.randao_reveal))
// state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR] = mix
func ProcessRandao(
beaconState *stateTrie.BeaconState,
body *ethpb.BeaconBlockBody,
) (*stateTrie.BeaconState, error) {
buf, proposerPub, domain, err := randaoSigningData(beaconState)
if err != nil {
return nil, err
}
if err := verifySignature(buf, proposerPub[:], body.RandaoReveal, domain); err != nil {
return nil, errors.Wrap(err, "could not verify block randao")
}
beaconState, err = ProcessRandaoNoVerify(beaconState, body)
if err != nil {
return nil, errors.Wrap(err, "could not process randao")
}
return beaconState, nil
}
// ProcessRandaoNoVerify generates a new randao mix to update
// in the beacon state's latest randao mixes slice.
//
// Spec pseudocode definition:
// # Mix it in
// state.latest_randao_mixes[get_current_epoch(state) % LATEST_RANDAO_MIXES_LENGTH] = (
// xor(get_randao_mix(state, get_current_epoch(state)),
// hash(body.randao_reveal))
// )
func ProcessRandaoNoVerify(
beaconState *stateTrie.BeaconState,
body *ethpb.BeaconBlockBody,
) (*stateTrie.BeaconState, error) {
currentEpoch := helpers.SlotToEpoch(beaconState.Slot())
// If block randao passed verification, we XOR the state's latest randao mix with the block's
// randao and update the state's corresponding latest randao mix value.
latestMixesLength := params.BeaconConfig().EpochsPerHistoricalVector
latestMixSlice, err := beaconState.RandaoMixAtIndex(currentEpoch % latestMixesLength)
if err != nil {
return nil, err
}
blockRandaoReveal := hashutil.Hash(body.RandaoReveal)
if len(blockRandaoReveal) != len(latestMixSlice) {
return nil, errors.New("blockRandaoReveal length doesnt match latestMixSlice length")
}
for i, x := range blockRandaoReveal {
latestMixSlice[i] ^= x
}
if err := beaconState.UpdateRandaoMixesAtIndex(currentEpoch%latestMixesLength, latestMixSlice); err != nil {
return nil, err
}
return beaconState, nil
}

Some files were not shown because too many files have changed in this diff Show More