-
Notifications
You must be signed in to change notification settings - Fork 3
state transition function #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
48b6157
state transition function
turuslan 94b774f
bound check
turuslan 02a9ae6
fix gcc
turuslan 2ca7a0a
Merge remote-tracking branch 'origin/master' into feature/stf
turuslan 96bd55e
remove todo
turuslan c600877
rename
turuslan d90c196
pr comment
turuslan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| /** | ||
| * Copyright Quadrivium LLC | ||
| * All Rights Reserved | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| #pragma once | ||
|
|
||
| #include <cmath> | ||
|
|
||
| #include <boost/assert.hpp> | ||
|
|
||
| #include "types/slot.hpp" | ||
|
|
||
| namespace lean { | ||
| inline bool isJustifiableSlot(Slot finalized_slot, Slot candidate) { | ||
| BOOST_ASSERT(candidate >= finalized_slot); | ||
| auto delta = candidate - finalized_slot; | ||
| return delta <= 5 | ||
| // any x^2 | ||
| or fmod(sqrt(delta), 1) == 0 | ||
| // any x^2+x | ||
| or fmod(sqrt(delta + 0.25), 1) == 0.5; | ||
| } | ||
| } // namespace lean |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,278 @@ | ||
| /** | ||
| * Copyright Quadrivium LLC | ||
| * All Rights Reserved | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| #include "blockchain/state_transition_function.hpp" | ||
|
|
||
| #include <boost/assert.hpp> | ||
|
|
||
| #include "blockchain/is_justifiable_slot.hpp" | ||
| #include "types/signed_block.hpp" | ||
| #include "types/state.hpp" | ||
|
|
||
| namespace lean { | ||
| constexpr BlockHash kZeroHash; | ||
|
|
||
| inline bool getBit(const std::vector<bool> &bits, size_t i) { | ||
| return i < bits.size() and bits.at(i); | ||
| } | ||
|
|
||
| // TODO(turuslan): spec doesn't rotate history | ||
| inline void setBit(std::vector<bool> &bits, size_t i) { | ||
| if (bits.size() <= i) { | ||
| bits.resize(i + 1); | ||
| } | ||
| bits.at(i) = true; | ||
| } | ||
|
|
||
| using Justifications = std::map<BlockHash, std::vector<bool>>; | ||
|
|
||
| /** | ||
| * Returns a map of `root -> justifications` constructed from the flattened | ||
| * data in the state. | ||
| */ | ||
| inline Justifications getJustifications(const State &state) { | ||
| auto &roots = state.justifications_roots.data(); | ||
| auto &validators = state.justifications_validators.data(); | ||
| Justifications justifications; | ||
| size_t offset = 0; | ||
| BOOST_ASSERT(validators.size() == roots.size() * VALIDATOR_REGISTRY_LIMIT); | ||
| for (auto &root : roots) { | ||
| auto next_offset = offset + VALIDATOR_REGISTRY_LIMIT; | ||
| std::vector<bool> bits{ | ||
| validators.begin() + offset, | ||
| validators.begin() + next_offset, | ||
| }; | ||
| justifications[root] = std::move(bits); | ||
| offset = next_offset; | ||
| } | ||
| return justifications; | ||
| } | ||
|
|
||
| /** | ||
| * Saves a map of `root -> justifications` back into the state's flattened | ||
| * data structure. | ||
| */ | ||
| inline void setJustifications(State &state, | ||
| const Justifications &justifications) { | ||
| auto &roots = state.justifications_roots.data(); | ||
| auto &validators = state.justifications_validators.data(); | ||
| roots.resize(0); | ||
turuslan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| roots.reserve(justifications.size()); | ||
| validators.resize(0); | ||
| validators.reserve(justifications.size() * VALIDATOR_REGISTRY_LIMIT); | ||
| for (auto &[root, bits] : justifications) { | ||
| BOOST_ASSERT(bits.size() == VALIDATOR_REGISTRY_LIMIT); | ||
| roots.push_back(root); | ||
| validators.insert(validators.end(), bits.begin(), bits.end()); | ||
| } | ||
| } | ||
|
|
||
| State StateTransitionFunction::generateGenesisState( | ||
| const Config &config) const { | ||
| BlockHeader header; | ||
| header.body_root = sszHash(BlockBody{}); | ||
| return State{ | ||
| .config = config, | ||
| .latest_block_header = header, | ||
| }; | ||
| } | ||
|
|
||
| Block StateTransitionFunction::genesisBlock(const State &state) const { | ||
| return Block{.state_root = sszHash(state)}; | ||
| } | ||
|
|
||
| outcome::result<State> StateTransitionFunction::stateTransition( | ||
| const SignedBlock &signed_block, | ||
| const State &parent_state, | ||
| bool check_state_root) const { | ||
| auto &block = signed_block.message; | ||
| auto state = parent_state; | ||
| // Process slots (including those with no blocks) since block | ||
| OUTCOME_TRY(processSlots(state, block.slot)); | ||
| // Process block | ||
| OUTCOME_TRY(processBlock(state, block)); | ||
| // Verify state root | ||
| if (check_state_root) { | ||
| auto state_root = sszHash(state); | ||
| if (block.state_root != state_root) { | ||
| return Error::STATE_ROOT_DOESNT_MATCH; | ||
| } | ||
| } | ||
| return std::move(state); | ||
| } | ||
|
|
||
| outcome::result<void> StateTransitionFunction::processSlots(State &state, | ||
| Slot slot) const { | ||
| if (state.slot >= slot) { | ||
| return Error::INVALID_SLOT; | ||
| } | ||
| while (state.slot < slot) { | ||
| processSlot(state); | ||
| ++state.slot; | ||
| } | ||
| return outcome::success(); | ||
| } | ||
|
|
||
| void StateTransitionFunction::processSlot(State &state) const { | ||
| // Cache latest block header state root | ||
| if (state.latest_block_header.state_root == kZeroHash) { | ||
| state.latest_block_header.state_root = sszHash(state); | ||
| } | ||
turuslan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| outcome::result<void> StateTransitionFunction::processBlock( | ||
| State &state, const Block &block) const { | ||
| OUTCOME_TRY(processBlockHeader(state, block)); | ||
| OUTCOME_TRY(processOperations(state, block.body)); | ||
| return outcome::success(); | ||
| } | ||
|
|
||
| outcome::result<void> StateTransitionFunction::processBlockHeader( | ||
| State &state, const Block &block) const { | ||
| // Verify that the slots match | ||
| if (block.slot != state.slot) { | ||
| return Error::INVALID_SLOT; | ||
| } | ||
| // Verify that the block is newer than latest block header | ||
| if (block.slot <= state.latest_block_header.slot) { | ||
| return Error::INVALID_SLOT; | ||
| } | ||
| // Verify that proposer index is the correct index | ||
| if (block.proposer_index != block.slot % state.config.num_validators) { | ||
turuslan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return Error::INVALID_PROPOSER; | ||
| } | ||
| // Verify that the parent matches | ||
| state.latest_block_header.updateHash(); | ||
| if (block.parent_root != state.latest_block_header.hash()) { | ||
| return Error::PARENT_ROOT_DOESNT_MATCH; | ||
| } | ||
|
|
||
| // If this was first block post genesis, 3sf mini special treatment is | ||
| // required to correctly set genesis block root as already justified and | ||
| // finalized. This is not possible at the time of genesis state generation | ||
| // and are set at zero bytes because genesis block is calculated using | ||
| // genesis state causing a circular dependency | ||
| if (state.latest_block_header.slot == 0) { | ||
turuslan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // block.parent_root is the genesis root | ||
| state.latest_justified.root = block.parent_root; | ||
| state.latest_finalized.root = block.parent_root; | ||
| } | ||
|
|
||
| // now that we can vote on parent, push it at its correct slot index in the | ||
| // structures | ||
| state.historical_block_hashes.push_back(block.parent_root); | ||
| // genesis block is always justified | ||
| state.justified_slots.push_back(state.latest_block_header.slot == 0); | ||
|
|
||
| // if there were empty slots, push zero hash for those ancestors | ||
| for (auto num_empty_slots = block.slot - state.latest_block_header.slot - 1; | ||
| num_empty_slots > 0; | ||
| --num_empty_slots) { | ||
| state.historical_block_hashes.push_back(kZeroHash); | ||
| state.justified_slots.push_back(false); | ||
| } | ||
|
|
||
| // Cache current block as the new latest block | ||
| state.latest_block_header = block.getHeader(); | ||
| // Overwritten in the next process_slot call | ||
| state.latest_block_header.state_root = kZeroHash; | ||
| return outcome::success(); | ||
| } | ||
|
|
||
| outcome::result<void> StateTransitionFunction::processOperations( | ||
| State &state, const BlockBody &body) const { | ||
| // process attestations | ||
| OUTCOME_TRY(processAttestations(state, body.attestations.data())); | ||
| // other operations will get added as the functionality evolves | ||
| return outcome::success(); | ||
| } | ||
|
|
||
| outcome::result<void> StateTransitionFunction::processAttestations( | ||
| State &state, const std::vector<SignedVote> &attestations) const { | ||
| // get justifications, justified slots and historical block hashes are | ||
| // already upto date as per the processing in process_block_header | ||
| auto justifications = getJustifications(state); | ||
|
|
||
| // From 3sf-mini/consensus.py - apply votes | ||
| for (auto &signed_vote : attestations) { | ||
| auto &vote = signed_vote.data; | ||
| if (vote.source.slot >= state.historical_block_hashes.size()) { | ||
| return Error::INVALID_VOTE_SOURCE_SLOT; | ||
| } | ||
| if (vote.target.slot >= state.historical_block_hashes.size()) { | ||
| return Error::INVALID_VOTE_TARGET_SLOT; | ||
| } | ||
| // Ignore votes whose source is not already justified, | ||
| // or whose target is not in the history, or whose target is not a | ||
| // valid justifiable slot | ||
| if (not getBit(state.justified_slots.data(), vote.source.slot) | ||
| // This condition is missing in 3sf mini but has been added here | ||
| // because we don't want to re-introduce the target again for | ||
| // remaining votes if the slot is already justified and its tracking | ||
| // already cleared out from justifications map | ||
| or getBit(state.justified_slots.data(), vote.target.slot) | ||
| or vote.source.root | ||
| != state.historical_block_hashes.data().at(vote.source.slot) | ||
| or vote.target.root | ||
| != state.historical_block_hashes.data().at(vote.target.slot) | ||
turuslan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| or vote.target.slot <= vote.source.slot | ||
| or not isJustifiableSlot(state.latest_finalized.slot, | ||
| vote.target.slot)) { | ||
| continue; | ||
| } | ||
|
|
||
| auto justifications_it = justifications.find(vote.target.root); | ||
| // Track attempts to justify new hashes | ||
| if (justifications_it == justifications.end()) { | ||
| justifications_it = | ||
| justifications.emplace(vote.target.root, std::vector<bool>{}).first; | ||
| justifications_it->second.resize(VALIDATOR_REGISTRY_LIMIT); | ||
| } | ||
|
|
||
| if (vote.validator_id >= justifications_it->second.size()) { | ||
| return Error::INVALID_VOTER; | ||
| } | ||
| justifications_it->second.at(vote.validator_id) = true; | ||
|
|
||
| size_t count = 0; | ||
| for (auto &&bit : justifications_it->second) { | ||
| if (bit) { | ||
| ++count; | ||
| } | ||
| } | ||
turuslan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // If 2/3 voted for the same new valid hash to justify | ||
| // in 3sf mini this is strict equality, but we have updated it to >= | ||
| // also have modified it from count >= (2 * state.config.num_validators) | ||
| // / 3 to prevent integer division which could lead to less than 2/3 of | ||
| // validators justifying specially if the num_validators is low in testing | ||
| // scenarios | ||
| if (3 * count >= 2 * state.config.num_validators) { | ||
xDimon marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| state.latest_justified = vote.target; | ||
| setBit(state.justified_slots.data(), vote.target.slot); | ||
| justifications.erase(vote.target.root); | ||
|
|
||
| // Finalization: if the target is the next valid justifiable hash after | ||
| // the source | ||
| auto any = false; | ||
| for (auto slot = vote.source.slot + 1; slot < vote.target.slot; | ||
| ++slot) { | ||
| if (isJustifiableSlot(state.latest_finalized.slot, slot)) { | ||
| any = true; | ||
| break; | ||
| } | ||
| } | ||
| if (not any) { | ||
| state.latest_finalized = vote.source; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // flatten and set updated justifications back to the state | ||
| setJustifications(state, justifications); | ||
| return outcome::success(); | ||
| } | ||
| } // namespace lean | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.