### Install Gocognit with Go Get Source: https://github.com/offchainlabs/prysm/blob/develop/tools/analyzers/gocognit/README.md Installs the gocognit command-line tool using the go get command. ```Shell go get github.com/uudashr/gocognit/cmd/gocognit ``` -------------------------------- ### Install Logrus Prefixed Formatter Source: https://github.com/offchainlabs/prysm/blob/develop/runtime/logging/logrus-prefixed-formatter/README.md Installs the formatter using the go get command. Ensure you are using the correct path for the Prysm fork. ```sh $ go get github.com/prysmaticlabs/prysm/runtime/logging/logrus-prefixed-formatter ``` -------------------------------- ### Install ethspecify Source: https://github.com/offchainlabs/prysm/blob/develop/specrefs/README.md Install the ethspecify tool using pipx. This is the initial step for managing specification references. ```bash pipx install ethspecify ``` -------------------------------- ### Gocognit CLI Usage Examples Source: https://github.com/offchainlabs/prysm/blob/develop/tools/analyzers/gocognit/README.md Provides examples of how to use the gocognit command-line tool to analyze Go code for cognitive complexity. ```Shell $ gocognit . $ gocognit main.go $ gocognit -top 10 src/ $ gocognit -over 25 docker $ gocognit -avg . ``` -------------------------------- ### Install Gocognit with Go Modules Source: https://github.com/offchainlabs/prysm/blob/develop/tools/analyzers/gocognit/README.md Installs the latest version of the gocognit command-line tool using Go modules. ```Shell go install github.com/uudashr/gocognit/cmd/gocognit@latest ``` -------------------------------- ### Flat Buffer Storage Layout Example Source: https://github.com/offchainlabs/prysm/blob/develop/beacon-chain/state/fieldtrie/doc.md Demonstrates the layout of trie nodes in a contiguous flat buffer and the use of an offsets table to map levels to their starting indices. This layout is cache-friendly for both full rebuilds and branch recomputation. ```text nodes = [A, B, C, D, H(A,B), H(C,D), H(H(A,B),H(C,D))] offsets = [0, 4, 6, 7] Level 0 (leaves): nodes[0..4) = A, B, C, D Level 1: nodes[4..6) = H(A,B), H(C,D) Level 2 (root): nodes[6..7) = H(H(A,B), H(C,D)) ``` -------------------------------- ### Pending Deposits Serialization Example Source: https://github.com/offchainlabs/prysm/blob/develop/consensus-types/hdiff/state_diff.md Illustrates the serialization of pending deposits, including a starting index and a diff slice. This method is used when the source and target states have overlapping pending deposit queues. ```text Source pending deposits: [A, B, C, D, E, F, G, H] Target pending deposits: [C, D, E, F, G, H, I, J, K] Serialized diff: pendingDepositIndex = 2, diffSlice = [I, J, K] ``` -------------------------------- ### Logfmt Output Example Source: https://github.com/offchainlabs/prysm/blob/develop/runtime/logging/logrus-prefixed-formatter/README.md Demonstrates the logfmt compatible output when a TTY is not attached. This format is useful for redirecting logs to systems that parse key-value pairs. ```text time="Oct 27 00:44:26" level=debug msg="Started observing beach" animal=walrus number=8 time="Oct 27 00:44:26" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 time="Oct 27 00:44:26" level=warning msg="The group's number increased tremendously!" number=122 omg=true time="Oct 27 00:44:26" level=debug msg="Temperature changes" temperature=-4 time="Oct 27 00:44:26" level=panic msg="It's over 9000!" animal=orca size=9009 time="Oct 27 00:44:26" level=fatal msg="The ice breaks!" number=100 omg=true exit status 1 ``` -------------------------------- ### Start Prysm Validator with Unencrypted Keys Source: https://github.com/offchainlabs/prysm/blob/develop/tools/unencrypted-keys-gen/README.md This command starts the Prysm validator client using a pre-generated JSON file of unencrypted keys. Ensure the path to the JSON file is correct. ```bash bazel run //validator -- --unencrypted-keys /path/to/output.json ``` -------------------------------- ### SSZ Query Package Usage Example Source: https://github.com/offchainlabs/prysm/blob/develop/encoding/ssz/query/doc.md Demonstrates the typical workflow for analyzing an SSZ object, parsing a path, calculating a generalized index, generating a Merkle proof, and extracting specific data bytes. ```go // 1. Analyze an SSZ object block := ðpb.BeaconBlock{...} info, err := query.AnalyzeObject(block) // 2. Parse a path path, err := query.ParsePath(".body.attestations[0].data.slot") // 3. Get the generalized index gindex, err := query.GetGeneralizedIndexFromPath(info, path) // 4. Generate a Merkle proof proof, err := info.Prove(gindex) // 5. Get offset and length to slice the SSZ-encoded bytes sszBytes, _ := block.MarshalSSZ() _, offset, length, err := query.CalculateOffsetAndLength(info, path) // slotBytes contains the SSZ-encoded value at the queried path slotBytes := sszBytes[offset : offset+length] ``` -------------------------------- ### Running Prometheus with Configuration Source: https://github.com/offchainlabs/prysm/blob/develop/monitoring/prometheus/README.md This command starts the Prometheus server using the specified configuration file. Make sure to replace 'your-prometheus-file.yml' with the actual path to your configuration. ```sh $ prometheus --config.file=your-prometheus-file.yml ``` -------------------------------- ### Example ENR Output Source: https://github.com/offchainlabs/prysm/blob/develop/tools/enr-calculator/README.md This is an example of the ENR output generated by the ENR Calculator tool. ```text INFO[0000] enr:-IS4QKk3gX9EqxA3x83AbCiyAnSuPDMvK52dC50Hm1XGDd5tEyQhM3VcJL-4b8kDg5APz_povv0Syqk0nancoNW-cq0BgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQM1E5yUsp9vDQj1tv3ZWXCvaFBvrPNdz8KPI1NhxfQWzIN1ZHCCB9A ``` -------------------------------- ### FieldTrie Lifecycle Example Source: https://github.com/offchainlabs/prysm/blob/develop/beacon-chain/state/fieldtrie/doc.md Illustrates the creation, copying, root computation, recomputation (with forking), and garbage collection of a FieldTrie. It shows how reference counts (Ref and DataRef) change at each step. ```Go package main import ( "fmt" "runtime" fieldtrie "github.com/prysmaticlabs/prysm/v5/beacon-chain/state/fieldtrie" "github.com/prysmaticlabs/prysm/v5/beacon-chain/state/state-native/types" ) func main() { // --------------------------------------------------------------- // Step 1: Create a new field trie (owned mode). // --------------------------------------------------------------- elements := make([][]byte, 8) for i := range elements { elements[i] = []byte{byte(i)} } trieA, err := fieldtrie.NewFieldTrie( types.BlockRoots, // field index types.BasicArray, // data type elements, // initial elements 8, // max capacity (determines trie depth) 0, // promotionThreshold (0 = use default) ) if err != nil { panic(err) } // trieA is in owned mode with its own flat buffer. // trieA.Ref = 1 (one handle: trieA) // trieA.DataRef = 0 (no overlay is using trieA as a base) // --------------------------------------------------------------- // Step 2: Compute the root of the trie (read-only). // --------------------------------------------------------------- rootA, err := trieA.TrieRoot() if err != nil { panic(err) } fmt.Printf("Root A: %x\n", rootA) // TrieRoot is a read-only operation — reference counts are unchanged. // trieA.Ref = 1 // trieA.DataRef = 0 // --------------------------------------------------------------- // Step 3: Copy the trie (lightweight, reference-shared copy). // --------------------------------------------------------------- trieB := trieA.CopyTrie() // CopyTrie increments the shared ref counter. // trieA and trieB point to the SAME underlying data. // trieA.Ref (== trieB.Ref) = 2 (two handles share the trie) // trieA.DataRef (== trieB.DataRef) = 0 // --------------------------------------------------------------- // Step 4: Recompute trieB with changed elements. // --------------------------------------------------------------- // Because Ref == 2 (shared), RecomputeTrie will fork before mutating. // The fork creates a new independent trie (trieC) in overlay mode, // pointing to trieA's flat buffer as its immutable base. changedIndices := []uint64{0, 3} newElements := make([][]byte, 8) copy(newElements, elements) newElements[0] = []byte{0xAA} newElements[3] = []byte{0xBB} trieC, rootC, err := trieB.RecomputeTrie(changedIndices, newElements) if err != nil { panic(err) } // trieB is now stale — the caller MUST use trieC instead. // Internally, fork() did the following: // - Created trieC with fresh Ref=1, DataRef=0. // - Incremented trieA.DataRef (trieC uses trieA's buffer as base). // - trieA/trieB still share Ref=2 (unchanged by the fork). // // After fork + recompute: // trieA.Ref = 2 (trieA and trieB still share) // trieA.DataRef = 1 (trieC's overlay references trieA's buffer) // trieC.Ref = 1 (only trieC holds the forked trie) // trieC.DataRef = 0 (no overlay is based on trieC) fmt.Printf("Root C: %x\n", rootC) // --------------------------------------------------------------- // Step 5: GC trieB — one of the two original shared handles. // --------------------------------------------------------------- trieB = nil runtime.GC() // The GC cleanup callback (cleanupRef) decrements the shared Ref. // trieA.Ref = 1 (only trieA remains) // trieA.DataRef = 1 (trieC's overlay still references trieA's buffer) // trieC.Ref = 1 // trieC.DataRef = 0 // --------------------------------------------------------------- // Step 6: GC trieC — the overlay is released. // --------------------------------------------------------------- _ = rootC trieC = nil runtime.GC() // The GC cleanup callbacks fire: // - cleanupRef on trieC.Ref → trieC.Ref decremented (now 0) // - cleanupRef on trieA.DataRef (via dataRefCleanup) → trieA.DataRef decremented // // trieA.Ref = 1 (trieA is still alive) // trieA.DataRef = 0 (no more overlays reference trieA's buffer) // trieA is no longer shared (Ref == 1 && DataRef == 0), // so future RecomputeTrie calls on trieA will mutate in place // without forking. // --------------------------------------------------------------- // Step 7: Recompute trieA in place (not shared anymore). // --------------------------------------------------------------- } ``` -------------------------------- ### Cyclomatic Complexity Example Source: https://github.com/offchainlabs/prysm/blob/develop/tools/analyzers/gocognit/README.md Illustrates the calculation of cyclomatic complexity for a switch statement. Each case and the switch itself increments the complexity count. ```Go func GetWords(number int) string { switch number { case 1: return "one" case 2: return "a couple" case 3: return "a few" default: return "lots" } } // Cyclomatic complexity = 4 ``` -------------------------------- ### Compute Start Slot of Epoch Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Calculates the starting slot number for a given epoch. Used to determine the beginning of an epoch's time window. ```python def compute_start_slot_at_epoch(epoch: Epoch) -> Slot: """ Return the start slot of ``epoch``. """ return Slot(epoch * SLOTS_PER_EPOCH) ``` -------------------------------- ### Cognitive Complexity Example Source: https://github.com/offchainlabs/prysm/blob/develop/tools/analyzers/gocognit/README.md Illustrates the calculation of cognitive complexity for a switch statement. Only the switch statement itself increments the complexity count. ```Go func GetWords(number int) { switch number { case 1: return "one" case 2: return "a couple" case 3: return "a few" default: return "lots" } } // Cognitive complexity = 1 ``` -------------------------------- ### Launch Prysm Validator with CLI Flags Source: https://github.com/offchainlabs/prysm/blob/develop/INTEROP.md Start the validator client with a specified number of validators and a suggested fee recipient. Ensure the data directory is set appropriately. ```bash bazel run //cmd/validator --config=minimal -- --datadir=/tmp/validator --interop-num-validators=256 --minimal-config --suggested-fee-recipient=0x8A04d14125D0FDCDc742F4A05C051De07232EDa4 ``` -------------------------------- ### Launch Prysm Beacon Chain with CLI Flags Source: https://github.com/offchainlabs/prysm/blob/develop/INTEROP.md Use this command to start the beacon node with minimal configuration for development. It requires specifying the deposit contract, data directory, and genesis state file. ```bash bazel run //cmd/beacon-chain --config=minimal -- \ --minimal-config \ --bootstrap-node= \ --deposit-contract 0x8A04d14125D0FDCDc742F4A05C051De07232EDa4 \ --datadir=/tmp/beacon-chain-minimal-devnet \ --force-clear-db \ --min-sync-peers=0 \ --genesis-state=/tmp/genesis.ssz \ --chain-config-file=/tmp/minimal.yaml ``` -------------------------------- ### View Go Execution Traces Source: https://github.com/offchainlabs/prysm/blob/develop/monitoring/tracing/README.md This command opens the collected trace data in the Go trace viewer. It automatically starts a local web server and opens the trace in your default browser. ```sh $ go tool trace trace.out ``` -------------------------------- ### Generate site_data.go with go-bindata Source: https://github.com/offchainlabs/prysm/blob/develop/validator/web/README.md Use the go-bindata tool to generate the site_data.go file from the Prysm web UI release. Ensure you have go-bindata version 4.0.2 or compatible installed. ```bash go-bindata -pkg web -nometadata -modtime 0 -o site_data.go prysm-web-ui/ ``` -------------------------------- ### Get Matching Source Attestations Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Retrieves pending attestations for the current or previous epoch. Asserts that the provided epoch is valid. ```python def get_matching_source_attestations(state: BeaconState, epoch: Epoch) -> Sequence[PendingAttestation]: assert epoch in (get_previous_epoch(state), get_current_epoch(state)) return state.current_epoch_attestations if epoch == get_current_epoch(state) else state.previous_epoch_attestations ``` -------------------------------- ### Basic Usage of Prefixed Formatter Source: https://github.com/offchainlabs/prysm/blob/develop/runtime/logging/logrus-prefixed-formatter/README.md Initializes the Logrus logger with the prefixed text formatter and demonstrates logging with fields. This setup is suitable for general application logging. ```go package main import ( prefixed "github.com/prysmaticlabs/prysm/runtime/logging/logrus-prefixed-formatter" "github.com/sirupsen/logrus" ) var log = logrus.New() func init() { log.Formatter = new(prefixed.TextFormatter) log.Level = logrus.DebugLevel } func main() { log.WithFields(logrus.Fields{ "prefix": "main", "animal": "walrus", "number": 8, }).Debug("Started observing beach") log.WithFields(logrus.Fields{ "prefix": "sensor", "temperature": -4, }).Info("Temperature changes") } ``` -------------------------------- ### Add and Update Go Dependencies with Bazel Source: https://github.com/offchainlabs/prysm/blob/develop/DEPENDENCIES.md After adding a new dependency using 'go get', run this command to update Bazel-managed dependencies and synchronize the 'deps.bzl' file. Ensure all dependencies are managed via 'deps.bzl' and not directly in the WORKSPACE file. ```bash go get github.com/OffchainLabs/example@v1.2.3 bazel run //:gazelle -- update-repos -from_file=go.mod -to_macro=deps.bzl%prysm_deps -prune=true ``` -------------------------------- ### Start Interactive Rebase Source: https://github.com/offchainlabs/prysm/blob/develop/CONTRIBUTING.md Initiate an interactive rebase to modify commit history. Replace 'commit-hash' with the output from the 'git merge-base' command. ```bash git rebase -i commit-hash ``` -------------------------------- ### Create Custom Traces with OpenCensus Source: https://github.com/offchainlabs/prysm/blob/develop/monitoring/tracing/README.md This Go code snippet demonstrates how to create a new trace span using OpenCensus. It starts a span named 'myOperation', executes a function, and then ends the span. Use the message context to correlate spans. ```go var msg p2p.Message var mySpan *trace.Span msg.Ctx, mySpan = trace.StartSpan(msg.Ctx, "myOperation") myOperation() mySpan.End() ``` -------------------------------- ### Default Color Scheme Source: https://github.com/offchainlabs/prysm/blob/develop/runtime/logging/logrus-prefixed-formatter/README.md Defines the default color scheme used by the formatter for different log levels and prefixes. This example shows the default styling for colored output. ```go InfoLevelStyle: "green", WarnLevelStyle: "yellow", ErrorLevelStyle: "red", FatalLevelStyle: "red", PanicLevelStyle: "red", DebugLevelStyle: "blue", PrefixStyle: "cyan", TimestampStyle: "black+h" ``` -------------------------------- ### Run Jaeger All-in-One Docker Image Source: https://github.com/offchainlabs/prysm/blob/develop/monitoring/tracing/README.md This command starts a Jaeger all-in-one Docker container, which includes all necessary components for collecting, storing, and visualizing traces. It exposes several ports for Jaeger's collector, agent, and UI. ```sh $ docker run -d --name jaeger -e COLLECTOR_ZIPKIN_HTTP_PORT=9411 -p 5775:5775/udp -p 6831:6831/udp -p 6832:6832/udp -p 5778:5778 -p 16686:16686 -p 14268:14268 -p 9411:9411 jaegertracing/all-in-one:1.6 ``` -------------------------------- ### Multiple Object Payload for Client Stats Source: https://github.com/offchainlabs/prysm/blob/develop/monitoring/clientstats/README.md This example shows how to send a payload containing multiple statistics objects, such as for a beacon node and system metrics. This is useful for reporting on different processes and system-level information simultaneously. ```json [ { "version":1, "timestamp":1618835497239, "process":"beaconnode", "cpu_process_seconds_total":6925, "memory_process_bytes":1175138304, "client_name":"lighthouse", "client_version":"1.1.3", "client_build":42, "sync_eth2_fallback_configured":false, "sync_eth2_fallback_connected":false, "validator_active":1, "validator_total":1 }, { "version":1, "timestamp":1618835497258, "process":"system", "cpu_cores":4, "cpu_threads":8, "cpu_node_system_seconds_total":1953818, "cpu_node_user_seconds_total":229215, "cpu_node_iowait_seconds_total":3761, "cpu_node_idle_seconds_total":1688619, "memory_node_bytes_total":33237434368, "memory_node_bytes_free":500150272, "memory_node_bytes_cached":13904945152, "memory_node_bytes_buffers":517832704, "disk_node_bytes_total":250436972544, "disk_node_bytes_free":124707479552, "disk_node_io_seconds":0, "disk_node_reads_total":3362272, "disk_node_writes_total":47766864, "network_node_bytes_total_receive":26546324572, "network_node_bytes_total_transmit":12057786467, "misc_node_boot_ts_seconds":1617707420, "misc_os":"unk" } ] ``` -------------------------------- ### Incremental Recomputation Example Source: https://github.com/offchainlabs/prysm/blob/develop/beacon-chain/state/fieldtrie/doc.md Illustrates the cost savings of incremental recomputation in a Merkle trie. Only nodes on the path from a changed leaf to the root need recomputing, reducing hash operations from O(n) to O(log n). ```text R R' / \ / \ H1 H2 H1 H2' / \ / \ / \ / \ H3 H4 H5 H6 H3 H4 H5' H6 /\ /\ /\ /\ /\ /\ /\ /\ A B C D E F G H A B C D E F' G H Full trie before After updating leaf F Recomputation path: 1. Hash the new leaf F' 2. H5' = Hash(E, F') ← sibling E is reused 3. H2' = Hash(H5', H6) ← sibling H6 is reused 4. R' = Hash(H1, H2') ← sibling H1 is reused Cost: 4 hashes instead of 15 (full rebuild). In general: O(log n) instead of O(n). ``` -------------------------------- ### Get Helper Indices for Merkle Proofs Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Calculates the generalized indices of all auxiliary nodes required to construct a Merkle proof for a given set of indices. ```python def get_helper_indices(indices: Sequence[GeneralizedIndex]) -> Sequence[GeneralizedIndex]: """ Get the generalized indices of all "extra" chunks in the tree needed to prove the chunks with the given generalized indices. Note that the decreasing order is chosen deliberately to ensure equivalence to the order of hashes in a regular single-item Merkle proof in the single-item case. """ all_helper_indices: Set[GeneralizedIndex] = set() all_path_indices: Set[GeneralizedIndex] = set() for index in indices: all_helper_indices = all_helper_indices.union(set(get_branch_indices(index))) all_path_indices = all_path_indices.union(set(get_path_indices(index))) return sorted(all_helper_indices.difference(all_path_indices), reverse=True) ``` -------------------------------- ### Get Block Root Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Retrieves the block root for the start of a specified recent epoch. Requires the state and the target epoch. ```python def get_block_root(state: BeaconState, epoch: Epoch) -> Root: """ Return the block root at the start of a recent ``epoch``. """ return get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch)) ``` -------------------------------- ### Get Domain Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Computes the signature domain based on the domain type, current epoch, and fork version. It selects the correct fork version based on whether the current epoch is before or after the fork epoch. ```python def get_domain(state: BeaconState, domain_type: DomainType, epoch: Epoch=None) -> Domain: """ Return the signature domain (fork version concatenated with domain type) of a message. """ epoch = get_current_epoch(state) if epoch is None else epoch fork_version = state.fork.previous_version if epoch < state.fork.epoch else state.fork.current_version return compute_domain(domain_type, fork_version, state.genesis_validators_root) ``` -------------------------------- ### Get Item Position in SSZ Chunk Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Determines the chunk index, start byte, and end byte for a specific element within an SSZ type. Handles lists, vectors, and containers. ```python def get_item_position(typ: SSZType, index_or_variable_name: Union[int, SSZVariableName]) -> Tuple[int, int, int]: """ Return three variables: (i) the index of the chunk in which the given element of the item is represented; (ii) the starting byte position within the chunk; (iii) the ending byte position within the chunk. For example: for a 6-item list of uint64 values, index=2 will return (0, 16, 24), index=5 will return (1, 8, 16) """ if issubclass(typ, Elements): index = int(index_or_variable_name) start = index * item_length(typ.elem_type) return start // 32, start % 32, start % 32 + item_length(typ.elem_type) elif issubclass(typ, Container): variable_name = index_or_variable_name return typ.get_field_names().index(variable_name), 0, item_length(get_elem_type(typ, variable_name)) else: raise Exception("Only lists/vectors/containers supported") ``` -------------------------------- ### Run HashTreeRoot Benchmark (Full State) Source: https://github.com/offchainlabs/prysm/blob/develop/testing/benchmark/README.md Execute the benchmark for calculating the HashTreeRoot on a full state. This command filters for the specific benchmark function. ```bash bazel test //beacon-chain/core/state:go_default_test --test_filter=BenchmarkHashTreeRoot_FullState --test_arg=-test.bench=BenchmarkHashTreeRoot_FullState ``` -------------------------------- ### Initialize Beacon State from Eth1 Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Creates a new `BeaconState` from Eth1 block data and deposits. Processes initial deposits and sets up validator effective balances and activation epochs. ```python def initialize_beacon_state_from_eth1(eth1_block_hash: Bytes32, eth1_timestamp: uint64, deposits: Sequence[Deposit]) -> BeaconState: fork = Fork( previous_version=GENESIS_FORK_VERSION, current_version=GENESIS_FORK_VERSION, epoch=GENESIS_EPOCH, ) state = BeaconState( genesis_time=eth1_timestamp + GENESIS_DELAY, fork=fork, eth1_data=Eth1Data(block_hash=eth1_block_hash, deposit_count=uint64(len(deposits))), latest_block_header=BeaconBlockHeader(body_root=hash_tree_root(BeaconBlockBody())), randao_mixes=[eth1_block_hash] * EPOCHS_PER_HISTORICAL_VECTOR, # Seed RANDAO with Eth1 entropy ) # Process deposits leaves = list(map(lambda deposit: deposit.data, deposits)) for index, deposit in enumerate(deposits): deposit_data_list = List[DepositData, 2**DEPOSIT_CONTRACT_TREE_DEPTH](*leaves[:index + 1]) state.eth1_data.deposit_root = hash_tree_root(deposit_data_list) process_deposit(state, deposit) # Process activations for index, validator in enumerate(state.validators): balance = state.balances[index] validator.effective_balance = min(balance - balance % EFFECTIVE_BALANCE_INCREMENT, MAX_EFFECTIVE_BALANCE) if validator.effective_balance == MAX_EFFECTIVE_BALANCE: validator.activation_eligibility_epoch = GENESIS_EPOCH validator.activation_epoch = GENESIS_EPOCH # Set genesis validators root for domain separation and chain versioning state.genesis_validators_root = hash_tree_root(state.validators) return state ``` -------------------------------- ### Calculate Eth1 Voting Period Start Time Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/validator.md Determines the start time of the current Eth1 voting period based on the current slot in the Beacon State. Uses `compute_time_at_slot`. ```python def voting_period_start_time(state: BeaconState) -> uint64: eth1_voting_period_start_slot = Slot(state.slot - state.slot % (EPOCHS_PER_ETH1_VOTING_PERIOD * SLOTS_PER_EPOCH)) return compute_time_at_slot(state, eth1_voting_period_start_slot) ``` -------------------------------- ### Run HashTreeRootState Benchmark (Full State) Source: https://github.com/offchainlabs/prysm/blob/develop/testing/benchmark/README.md Execute the benchmark for calculating the HashTreeRootState on a full state. This command filters for the specific benchmark function. ```bash bazel test //beacon-chain/core/state:go_default_test --test_filter=BenchmarkHashTreeRootState_FullState --test_arg=-test.bench=BenchmarkHashTreeRootState_FullState ``` -------------------------------- ### Run ExecuteStateTransition Benchmark (With Cache) Source: https://github.com/offchainlabs/prysm/blob/develop/testing/benchmark/README.md Execute the benchmark for processing a state transition with caching enabled. This command filters for the specific benchmark function. ```bash bazel test //beacon-chain/core/state:go_default_test --test_filter=BenchmarkExecuteStateTransition_WithCache --test_arg=-test.bench=BenchmarkExecuteStateTransition_WithCache ``` -------------------------------- ### Get Generalized Index Bit Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Retrieves a specific bit from a generalized index. ```python def get_generalized_index_bit(index: GeneralizedIndex, position: int) -> bool: """ Return the given bit of a generalized index. """ return (index & (1 << position)) > 0 ``` -------------------------------- ### Get Generalized Index Parent Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Calculates the parent index of a given generalized index. ```python def generalized_index_parent(index: GeneralizedIndex) -> GeneralizedIndex: return GeneralizedIndex(index // 2) ``` -------------------------------- ### Get Generalized Index Sibling Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Calculates the sibling index of a given generalized index. ```python def generalized_index_sibling(index: GeneralizedIndex) -> GeneralizedIndex: return GeneralizedIndex(index ^ 1) ``` -------------------------------- ### Get Execution Payload Envelope by Slot Source: https://github.com/offchainlabs/prysm/blob/develop/changelog/james-prysm_execution-payload-envelope-rest.md Retrieves the execution payload envelope for a specific slot. ```APIDOC ## GET /eth/v1/validator/execution_payload_envelope/{slot} ### Description Retrieves the execution payload envelope for a specific slot. ### Method GET ### Endpoint /eth/v1/validator/execution_payload_envelope/{slot} ### Parameters #### Path Parameters - **slot** (integer) - Required - The slot for which to retrieve the execution payload envelope. ``` -------------------------------- ### Run ExecuteStateTransition Benchmark (Full Block) Source: https://github.com/offchainlabs/prysm/blob/develop/testing/benchmark/README.md Execute the benchmark for processing a full block state transition. This command filters for the specific benchmark function. ```bash bazel test //beacon-chain/core/state:go_default_test --test_filter=BenchmarkExecuteStateTransition_FullBlock --test_arg=-test.bench=BenchmarkExecuteStateTransition_FullBlock ``` -------------------------------- ### Get Generalized Index Length Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Calculates the length of a path represented by a generalized index in a Merkle tree. ```python def get_generalized_index_length(index: GeneralizedIndex) -> int: """ Return the length of a path represented by a generalized index. """ return int(log2(index)) ``` -------------------------------- ### Get Path Indices Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Retrieves the generalized indices of all nodes along the path from a given tree index to the root. ```python def get_path_indices(tree_index: GeneralizedIndex) -> Sequence[GeneralizedIndex]: """ Get the generalized indices of the chunks along the path from the chunk with the given tree index to the root. """ o = [tree_index] while o[-1] > 1: o.append(generalized_index_parent(o[-1])) return o[:-1] ``` -------------------------------- ### Run Nightly Spectests Source: https://github.com/offchainlabs/prysm/blob/develop/testing/spectest/README.md Download and run nightly spectests from GitHub by setting the CONSENSUS_SPEC_TESTS_VERSION environment variable. A GITHUB_TOKEN is required. ```bash bazel test //... --test_tag_filters=spectest --repo_env=CONSENSUS_SPEC_TESTS_VERSION=nightly ``` ```bash bazel test //... --test_tag_filters=spectest --repo_env=CONSENSUS_SPEC_TESTS_VERSION=nightly-21422848633 ``` -------------------------------- ### Build with Bazel Release Configuration Source: https://github.com/offchainlabs/prysm/blob/develop/DEPENDENCIES.md Use this command to build Prysm binaries with release configurations, enabling compile-time optimizations and production build settings. This is recommended for production builds. ```bash bazel build //beacon-chain --config=release ``` -------------------------------- ### Download and Parse Specs Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/README.md Command to download and parse Ethereum consensus specifications into a local directory. ```bash bazel run //tools/specs-checker download -- --dir=$PWD/tools/specs-checker/data ``` -------------------------------- ### Run Manual State Transition with Pcli Source: https://github.com/offchainlabs/prysm/blob/develop/tools/pcli/README.md Use this command to perform a manual state transition by specifying the paths to the block, pre-state, and expected post-state files. ```bash bazel run //tools/pcli:pcli -- state-transition --block-path /path/to/block.ssz --pre-state-path /path/to/state.ssz ``` -------------------------------- ### Get Head Deltas Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Calculates attester rewards and penalties for head votes. It utilizes the `get_attestation_component_deltas` function for common calculations. ```python def get_head_deltas(state: BeaconState) -> Tuple[Sequence[Gwei], Sequence[Gwei]]: """ Return attester micro-rewards/penalties for head-vote for each validator. """ matching_head_attestations = get_matching_head_attestations(state, get_previous_epoch(state)) return get_attestation_component_deltas(state, matching_head_attestations) ``` -------------------------------- ### Run All Spectests Source: https://github.com/offchainlabs/prysm/blob/develop/testing/spectest/README.md Execute all spectests using Bazel. Ensure the 'spectest' tag filter is applied. ```bash bazel test //... --test_tag_filters=spectest ``` -------------------------------- ### Get Target Deltas Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Calculates attester rewards and penalties specifically for target votes. Leverages `get_attestation_component_deltas` for shared logic. ```python def get_target_deltas(state: BeaconState) -> Tuple[Sequence[Gwei], Sequence[Gwei]]: """ Return attester micro-rewards/penalties for target-vote for each validator. """ matching_target_attestations = get_matching_target_attestations(state, get_previous_epoch(state)) return get_attestation_component_deltas(state, matching_target_attestations) ``` -------------------------------- ### Check All Project Specs Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/README.md Command to check all reference comments against Python specifications for the entire project. ```bash bazel run //tools/specs-checker check -- --dir $PWD ``` -------------------------------- ### Get Source Deltas Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Calculates attester rewards and penalties specifically for source votes. Uses shared logic from `get_attestation_component_deltas`. ```python def get_source_deltas(state: BeaconState) -> Tuple[Sequence[Gwei], Sequence[Gwei]]: """ Return attester micro-rewards/penalties for source-vote for each validator. """ matching_source_attestations = get_matching_source_attestations(state, get_previous_epoch(state)) return get_attestation_component_deltas(state, matching_source_attestations) ``` -------------------------------- ### Get Matching Head Attestations Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Filters attestations to those matching the head block root at their respective slots. Relies on `get_matching_target_attestations`. ```python def get_matching_head_attestations(state: BeaconState, epoch: Epoch) -> Sequence[PendingAttestation]: return [ a for a in get_matching_target_attestations(state, epoch) if a.data.beacon_block_root == get_block_root_at_slot(state, a.data.slot) ] ``` -------------------------------- ### Get Matching Target Attestations Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Filters attestations to those matching the target block root for a given epoch. Relies on `get_matching_source_attestations`. ```python def get_matching_target_attestations(state: BeaconState, epoch: Epoch) -> Sequence[PendingAttestation]: return [ a for a in get_matching_source_attestations(state, epoch) if a.data.target.root == get_block_root(state, epoch) ] ``` -------------------------------- ### Run All Analyzer Unit Tests Source: https://github.com/offchainlabs/prysm/blob/develop/tools/analyzers/README.md Execute this command in the project root to run all unit tests for the analyzers. This is necessary because Bazel ignores these tests, and they are not part of the CI pipeline. ```bash go test ./tools/analyzers/... ``` -------------------------------- ### Generate ENR with Private Key, IP, and Port Source: https://github.com/offchainlabs/prysm/blob/develop/tools/enr-calculator/README.md Use this command to generate a node's ENR by providing its private key, IP address, and UDP port. The output will be the node's ENR. ```bash bazel run //tools/enr-calculator:enr-calculator -- --private CAISIJXSWjkbgprwuo01QCRegULoNIOZ0yTl1fLz5N0SsJCS --ipAddress 127.0.0.1 --port 2000 ``` -------------------------------- ### Get Current Epoch Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Retrieves the current epoch based on the state's current slot. This is a fundamental timekeeping function. ```python def get_current_epoch(state: BeaconState) -> Epoch: """ Return the current epoch. """ return compute_epoch_at_slot(state.slot) ``` -------------------------------- ### Get Block Ancestor Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/fork-choice.md Recursively finds the root of a block at a specific slot, traversing up the parent links in the block tree. ```python 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) elif block.slot == slot: return root else: # root is older than queried slot, thus a skip slot. Return most recent root prior to slot return root ``` -------------------------------- ### Initialize Fork Choice Store Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/fork-choice.md Creates and initializes the `Store` object for the fork choice algorithm, setting up initial checkpoints and block/state mappings based on an anchor state and block. ```python def get_forkchoice_store(anchor_state: BeaconState, anchor_block: BeaconBlock) -> Store: assert anchor_block.state_root == hash_tree_root(anchor_state) anchor_root = hash_tree_root(anchor_block) anchor_epoch = get_current_epoch(anchor_state) justified_checkpoint = Checkpoint(epoch=anchor_epoch, root=anchor_root) finalized_checkpoint = Checkpoint(epoch=anchor_epoch, root=anchor_root) return Store( time=uint64(anchor_state.genesis_time + SECONDS_PER_SLOT * anchor_state.slot), genesis_time=anchor_state.genesis_time, justified_checkpoint=justified_checkpoint, finalized_checkpoint=finalized_checkpoint, best_justified_checkpoint=justified_checkpoint, blocks={anchor_root: copy(anchor_block)}, block_states={anchor_root: copy(anchor_state)}, checkpoint_states={justified_checkpoint: copy(anchor_state)}, ) ``` -------------------------------- ### Get Branch Indices Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Retrieves the generalized indices of sibling nodes along the path from a given tree index to the root. ```python def get_branch_indices(tree_index: GeneralizedIndex) -> Sequence[GeneralizedIndex]: """ Get the generalized indices of the sister chunks along the path from the chunk with the given tree index to the root. """ o = [generalized_index_sibling(tree_index)] while o[-1] > 1: o.append(generalized_index_sibling(generalized_index_parent(o[-1]))) return o[:-1] ``` -------------------------------- ### Define Specification Directories Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/README.md Specifies the directories and files within the Ethereum consensus specs to be downloaded and parsed. ```go var specDirs = map[string][]string{ "specs/phase0": { "beacon-chain.md", "fork-choice.md", "validator.md", "weak-subjectivity.md", }, "ssz": { "merkle-proofs.md", }, } ``` -------------------------------- ### Get Inclusion Delay Deltas Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Calculates proposer and inclusion delay rewards/penalties. It iterates through matching source attestations to determine eligibility. ```python def get_inclusion_delay_deltas(state: BeaconState) -> Tuple[Sequence[Gwei], Sequence[Gwei]]: """ Return proposer and inclusion delay micro-rewards/penalties for each validator. """ rewards = [Gwei(0) for _ in range(len(state.validators))] matching_source_attestations = get_matching_source_attestations(state, get_previous_epoch(state)) for index in get_unslashed_attesting_indices(state, matching_source_attestations): attestation = min([ a for a in matching_source_attestations ``` -------------------------------- ### Get Current Slot Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/fork-choice.md Determines the current slot number based on the genesis slot and the number of slots elapsed since genesis. ```python def get_current_slot(store: Store) -> Slot: return Slot(GENESIS_SLOT + get_slots_since_genesis(store)) ``` -------------------------------- ### Test Local Builds for Supported Platforms Source: https://github.com/offchainlabs/prysm/blob/develop/tools/cross-toolchain/README.md Tests local builds for various platforms using Bazel. Each command specifies the release configuration and the target platform configuration (e.g., linux_amd64, linux_arm64_docker). ```bash bazel build --config=release --config=linux_amd64 --config=llvm //cmd/beacon-chain //cmd/validator //cmd/client-stats //cmd/prysmctl bazel build --config=release --config=linux_arm64_docker //cmd/beacon-chain //cmd/validator //cmd/client-stats //cmd/prysmctl bazel build --config=release --config=osx_amd64_docker //cmd/beacon-chain //cmd/validator //cmd/client-stats //cmd/prysmctl bazel build --config=release --config=osx_arm64_docker //cmd/beacon-chain //cmd/validator //cmd/client-stats //cmd/prysmctl bazel build --config=release --config=windows_amd64_docker //cmd/beacon-chain //cmd/validator //cmd/client-stats //cmd/prysmctl ``` -------------------------------- ### Get Generalized Index Child Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Calculates the child index of a given generalized index, specifying whether it's on the right side. ```python def generalized_index_child(index: GeneralizedIndex, right_side: bool) -> GeneralizedIndex: return GeneralizedIndex(index * 2 + right_side) ``` -------------------------------- ### Update Go Protobuf and SSZ Files Source: https://github.com/offchainlabs/prysm/blob/develop/DEPENDENCIES.md Run these scripts to ensure generated Go protobuf and SSZ files are up to date. This is crucial for users relying on vanilla Go build processes. ```bash ./hack/update-go-pbs.sh ./hack/update-go-ssz.sh ``` -------------------------------- ### Compute Slots Since Epoch Start Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/fork-choice.md Calculates the number of slots that have passed since the beginning of the current epoch for a given slot. ```python def compute_slots_since_epoch_start(slot: Slot) -> int: return slot - compute_start_slot_at_epoch(compute_epoch_at_slot(slot)) ``` -------------------------------- ### Concatenate Generalized Indices Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/ssz/merkle-proofs.md Combines multiple generalized indices to represent a path from a starting point to an ending point in a Merkle tree. ```python def concat_generalized_indices(*indices: GeneralizedIndex) -> GeneralizedIndex: """ Given generalized indices i1 for A -> B, i2 for B -> C .... i_n for Y -> Z, returns the generalized index for A -> Z. """ o = GeneralizedIndex(1) for i in indices: o = GeneralizedIndex(o * get_power_of_two_floor(i) + (i - get_power_of_two_floor(i))) return o ``` -------------------------------- ### Clone Prysm Repository Source: https://github.com/offchainlabs/prysm/blob/develop/CONTRIBUTING.md Clone the Prysm repository to your local machine within your Go workspace. This sets up the necessary directory structure. ```bash $ mkdir -p $GOPATH/src/github.com/OffchainLabs $ cd $GOPATH/src/github.com/OffchainLabs $ git clone https://github.com/OffchainLabs/prysm.git $ cd $GOPATH/src/github.com/OffchainLabs/prysm ``` -------------------------------- ### Get Eligible Validator Indices Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Retrieves indices of validators that are eligible for rewards or penalties. Includes active validators and those who are slashed but not yet withdrawable. ```python def get_eligible_validator_indices(state: BeaconState) -> Sequence[ValidatorIndex]: previous_epoch = get_previous_epoch(state) return [ ValidatorIndex(index) for index, v in enumerate(state.validators) if is_active_validator(v, previous_epoch) or (v.slashed and previous_epoch + 1 < v.withdrawable_epoch) ] ``` -------------------------------- ### Configure Bazel WORKSPACE for patching Source: https://github.com/offchainlabs/prysm/blob/develop/third_party/README.md Integrate a local patch into the Bazel build configuration by specifying the patch file and arguments in the go_repository rule. ```bazel go_repository( name = "com_github_prysmaticlabs_ethereumapis", commit = "367ca574419a062ae26818f60bdeb5751a6f538", patch_args = ["-p1"], patches = [ "//third_party:com_github_prysmaticlabs_ethereumapis-tags.patch", ], importpath = "github.com/prysmaticlabs/ethereumapis", ) ``` -------------------------------- ### Get Total Active Balance Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Computes the total effective balance of all active validators in the current epoch. It leverages the `get_total_balance` function for the calculation. ```python def get_total_active_balance(state: BeaconState) -> Gwei: """ Return the combined effective balance of the active validators. Note: ``get_total_balance`` returns ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero. """ return get_total_balance(state, set(get_active_validator_indices(state, get_current_epoch(state)))) ``` -------------------------------- ### Get Seed Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Retrieves the seed for a given epoch and domain type. Seeds are used in various consensus mechanisms, including randomness generation. ```python def get_seed(state: BeaconState, epoch: Epoch, domain_type: DomainType) -> Bytes32: """ Return the seed at ``epoch``. ``` -------------------------------- ### Switch to Feature Branch Source: https://github.com/offchainlabs/prysm/blob/develop/CONTRIBUTING.md Ensure you are working on your newly created feature branch before making any code modifications. ```bash $ git checkout feature-in-progress-branch ``` -------------------------------- ### Get Validator Churn Limit Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Calculates the maximum number of validators that can be added or removed per epoch. Based on the number of active validators. ```python def get_validator_churn_limit(state: BeaconState) -> uint64: """ Return the validator churn limit for the current epoch. """ active_validator_indices = get_active_validator_indices(state, get_current_epoch(state)) return max(MIN_PER_EPOCH_CHURN_LIMIT, uint64(len(active_validator_indices)) // CHURN_LIMIT_QUOTIENT) ``` -------------------------------- ### Get Active Validator Indices Source: https://github.com/offchainlabs/prysm/blob/develop/tools/specs-checker/data/specs/phase0/beacon-chain.md Returns a list of active validator indices for a given epoch. Filters validators based on their activation status. ```python def get_active_validator_indices(state: BeaconState, epoch: Epoch) -> Sequence[ValidatorIndex]: """ Return the sequence of active validator indices at ``epoch``. """ return [ValidatorIndex(i) for i, v in enumerate(state.validators) if is_active_validator(v, epoch)] ``` -------------------------------- ### Gocognit Output Format Source: https://github.com/offchainlabs/prysm/blob/develop/tools/analyzers/gocognit/README.md Describes the format of the output generated by the gocognit command-line tool, showing complexity, package, function name, and file location. ```Shell ```