# beacon_chain # Copyright (c) 2018-2022 Status Research & Development GmbH # Licensed and distributed under either of # * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT). # * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0). # at your option. This file may not be copied, modified, or distributed except according to those terms. {.push raises: [Defect].} ## This module contains signature verification helpers corresponding to those ## in signatures.nim, for use with signature sets / batch signature verification ## The functions follow the same structure and use the same arguments, except ## that the flow is split into separate collection and verification steps. import # Status lib blscurve, stew/[byteutils, results], taskpools, bearssl, # Internal "."/[helpers, beaconstate, forks, signatures], "."/datatypes/[altair, bellatrix, phase0] export results, altair, phase0, taskpools, bearssl, signatures type TaskPoolPtr* = TaskPool BatchVerifier* = object sigVerifCache*: BatchedBLSVerifierCache ##\ ## A cache for batch BLS signature verification contexts rng*: ref BrHmacDrbgContext ##\ ## A reference to the Nimbus application-wide RNG taskpool*: TaskPoolPtr func `$`*(s: SignatureSet): string = "(pubkey: 0x" & s.pubkey.toHex() & ", signing_root: 0x" & s.message.toHex() & ", signature: 0x" & s.signature.toHex() & ')' # Important: # - Due to lazy loading, when we do crypto verification # and only then state-transition verification, # there is no guarantee that pubkeys and signatures received are valid # unlike when Nimbus did eager loading which ensured they were correct beforehand template loadOrExit(signature: ValidatorSig, error: cstring): untyped = ## Load a BLS signature from a raw signature ## Exits the **caller** with false if the signature is invalid let sig = signature.load() if sig.isNone: return err(error) # this exits the calling scope, as templates are inlined. sig.unsafeGet() func init(T: type SignatureSet, pubkey: CookedPubKey, signing_root: Eth2Digest, signature: CookedSig): T = ## Add a new signature set triplet (pubkey, message, signature) ## to a collection of signature sets for batch verification. ( blscurve.PublicKey(pubkey), signing_root.data, blscurve.Signature(signature) ) proc aggregateAttesters( validatorIndices: openArray[uint64|ValidatorIndex], validatorKeys: auto, ): Result[CookedPubKey, cstring] = if validatorIndices.len == 0: # Aggregation spec requires non-empty collection # - https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04 # Eth2 spec requires at least one attesting index in attestation # - https://github.com/ethereum/consensus-specs/blob/v1.1.9/specs/phase0/beacon-chain.md#is_valid_indexed_attestation return err("aggregateAttesters: no attesting indices") let firstKey = validatorKeys.load(validatorIndices[0]) if not firstKey.isSome(): return err("aggregateAttesters: invalid attesting index") var attestersAgg{.noinit.}: AggregatePublicKey attestersAgg.init(firstKey.get()) for i in 1 ..< validatorIndices.len: let key = validatorKeys.load(validatorIndices[i]) if not key.isSome(): return err("aggregateAttesters: invalid attesting index") attestersAgg.aggregate(key.get()) ok(finish(attestersAgg)) proc aggregateAttesters( validatorIndices: openArray[uint64|ValidatorIndex], bits: auto, validatorKeys: auto, ): Result[CookedPubKey, cstring] = if validatorIndices.len == 0: # Aggregation spec requires non-empty collection # - https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04 # Eth2 spec requires at least one attesting index in attestation # - https://github.com/ethereum/consensus-specs/blob/v1.1.9/specs/phase0/beacon-chain.md#is_valid_indexed_attestation return err("aggregateAttesters: no attesting indices") var attestersAgg{.noinit.}: AggregatePublicKey var inited = false for i in 0..= BeaconStateFork.Altair and (signed_block is altair.SignedBeaconBlock or signed_block is bellatrix.SignedBeaconBlock): if signed_block.message.body.sync_aggregate.sync_committee_bits.countOnes() == 0: if signed_block.message.body.sync_aggregate.sync_committee_signature != ValidatorSig.infinity(): return err("collectSignatureSets: empty sync aggregates need signature of point at infinity") else: let current_sync_committee = state.data.get_sync_committee_cache(cache).current_sync_committee previous_slot = max(state.data.slot, Slot(1)) - 1 beacon_block_root = get_block_root_at_slot(state.data, previous_slot) pubkey = ? aggregateAttesters( current_sync_committee, signed_block.message.body.sync_aggregate.sync_committee_bits, validatorKeys) sigs.add sync_committee_message_signature_set( fork, genesis_validators_root, previous_slot, beacon_block_root, pubkey, signed_block.message.body.sync_aggregate.sync_committee_signature.loadOrExit( "collectSignatureSets: cannot load signature")) ok() proc batchVerify*(verifier: var BatchVerifier, sigs: openArray[SignatureSet]): bool = var bytes: array[32, byte] verifier.rng[].brHmacDrbgGenerate(bytes) try: verifier.taskpool.batchVerify(verifier.sigVerifCache, sigs, bytes) except Exception as exc: raiseAssert exc.msg # Shouldn't happen