2018-11-28 19:49:03 +00:00
|
|
|
# beacon_chain
|
2020-03-14 21:54:45 +00:00
|
|
|
# Copyright (c) 2018-2020 Status Research & Development GmbH
|
2018-11-28 19:49:03 +00:00
|
|
|
# Licensed and distributed under either of
|
2019-11-25 15:30:02 +00:00
|
|
|
# * 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).
|
2018-11-28 19:49:03 +00:00
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
|
|
|
# At the time of writing, the exact definitions of what should be used for
|
|
|
|
# cryptography in the spec is in flux, with sizes and test vectors still being
|
|
|
|
# hashed out. This layer helps isolate those chagnes.
|
|
|
|
|
2019-12-10 14:20:40 +00:00
|
|
|
# BLS signatures can be combined such that multiple signatures are aggregated.
|
|
|
|
# Each time a new signature is added, the corresponding public key must be
|
|
|
|
# added to the verification key as well - if a key signs twice, it must be added
|
|
|
|
# twice to the verification key. Aggregated signatures can be combined
|
|
|
|
# arbitrarily (like addition) as long as public keys are aggregated in the same
|
|
|
|
# way.
|
2018-12-27 20:14:37 +00:00
|
|
|
#
|
2019-12-10 14:20:40 +00:00
|
|
|
# In eth2, we use a single bit to record which keys have signed, thus we cannot
|
|
|
|
# combined overlapping aggregates - ie if we have an aggregate of signatures of
|
|
|
|
# A, B and C, and another with B, C and D, we cannot practically combine them
|
|
|
|
# even if in theory it is possible to allow this in BLS.
|
2018-12-27 20:14:37 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
2018-11-28 19:49:03 +00:00
|
|
|
import
|
2020-03-04 21:27:11 +00:00
|
|
|
# Internal
|
2020-04-11 08:51:07 +00:00
|
|
|
./digest, ../ssz/types,
|
2020-03-04 21:27:11 +00:00
|
|
|
# Status
|
2020-04-11 08:51:07 +00:00
|
|
|
stew/[endians2, objects, results, byteutils],
|
|
|
|
nimcrypto/sysrand,
|
|
|
|
blscurve,
|
2020-03-04 21:27:11 +00:00
|
|
|
chronicles,
|
2020-04-11 08:51:07 +00:00
|
|
|
json_serialization,
|
2020-03-04 21:27:11 +00:00
|
|
|
# Standard library
|
|
|
|
hashes
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
export results, json_serialization
|
2020-03-04 21:27:11 +00:00
|
|
|
|
|
|
|
# Type definitions
|
|
|
|
# ----------------------------------------------------------------------
|
2018-11-28 19:49:03 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
const
|
|
|
|
RawSigSize* = 96
|
|
|
|
RawPubKeySize* = 48
|
|
|
|
RawPrivKeySize* = 48
|
|
|
|
|
2018-11-28 19:49:03 +00:00
|
|
|
type
|
2019-07-03 07:35:05 +00:00
|
|
|
BlsValueType* = enum
|
|
|
|
Real
|
|
|
|
OpaqueBlob
|
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
BlsValue*[N: static int, T] = object
|
2019-07-03 07:35:05 +00:00
|
|
|
# TODO This is a temporary type needed until we sort out the
|
|
|
|
# issues with invalid BLS values appearing in the SSZ test suites.
|
|
|
|
case kind*: BlsValueType
|
|
|
|
of Real:
|
|
|
|
blsValue*: T
|
|
|
|
of OpaqueBlob:
|
2020-04-11 08:51:07 +00:00
|
|
|
blob*: array[N, byte]
|
2019-07-03 07:35:05 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
ValidatorPubKey* = BlsValue[RawPubKeySize, blscurve.PublicKey]
|
2019-07-03 07:35:05 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
ValidatorPrivKey* = distinct blscurve.SecretKey
|
2019-07-03 07:35:05 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
ValidatorSig* = BlsValue[RawSigSize, blscurve.Signature]
|
2019-07-03 07:35:05 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
BlsCurveType* = ValidatorPrivKey | ValidatorPubKey | ValidatorSig
|
|
|
|
|
|
|
|
BlsResult*[T] = Result[T, cstring]
|
2018-11-29 01:08:34 +00:00
|
|
|
|
2019-07-03 07:35:05 +00:00
|
|
|
func `==`*(a, b: BlsValue): bool =
|
|
|
|
if a.kind != b.kind: return false
|
|
|
|
if a.kind == Real:
|
|
|
|
return a.blsValue == b.blsValue
|
|
|
|
else:
|
|
|
|
return a.blob == b.blob
|
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
template `==`*[N, T](a: BlsValue[N, T], b: T): bool =
|
2019-07-03 07:35:05 +00:00
|
|
|
a.blsValue == b
|
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
template `==`*[N, T](a: T, b: BlsValue[N, T]): bool =
|
2019-07-03 07:35:05 +00:00
|
|
|
a == b.blsValue
|
|
|
|
|
2020-03-04 21:27:11 +00:00
|
|
|
# API
|
|
|
|
# ----------------------------------------------------------------------
|
2020-04-17 09:44:21 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v0.11.1/specs/phase0/beacon-chain.md#bls-signatures
|
2020-03-04 21:27:11 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
func toPubKey*(privkey: ValidatorPrivKey): ValidatorPubKey =
|
2020-03-04 21:27:11 +00:00
|
|
|
## Create a private key from a public key
|
|
|
|
# Un-specced in either hash-to-curve or Eth2
|
|
|
|
# TODO: Test suite should use `keyGen` instead
|
2019-07-03 07:35:05 +00:00
|
|
|
when ValidatorPubKey is BlsValue:
|
2020-04-11 08:51:07 +00:00
|
|
|
ValidatorPubKey(kind: Real, blsValue: SecretKey(privkey).privToPub())
|
2019-07-03 07:35:05 +00:00
|
|
|
elif ValidatorPubKey is array:
|
2020-03-04 21:27:11 +00:00
|
|
|
privkey.getKey.getBytes
|
2019-07-03 07:35:05 +00:00
|
|
|
else:
|
2020-03-04 21:27:11 +00:00
|
|
|
privkey.getKey
|
|
|
|
|
2020-03-30 23:40:24 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v0.11.1/specs/phase0/beacon-chain.md#bls-signatures
|
2020-03-04 21:27:11 +00:00
|
|
|
func aggregate*[T](values: openarray[ValidatorSig]): ValidatorSig =
|
|
|
|
## Aggregate arrays of sequences of Validator Signatures
|
|
|
|
## This assumes that they are real signatures
|
|
|
|
|
|
|
|
result = BlsValue[T](kind: Real, blsValue: values[0].BlsValue)
|
|
|
|
|
|
|
|
for i in 1 ..< values.len:
|
|
|
|
result.blsValue.aggregate(values[i].blsValue)
|
|
|
|
|
|
|
|
func aggregate*(x: var ValidatorSig, other: ValidatorSig) =
|
|
|
|
## Aggregate 2 Validator Signatures
|
|
|
|
## This assumes that they are real signatures
|
|
|
|
x.blsValue.aggregate(other.blsValue)
|
|
|
|
|
2020-04-17 09:44:21 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v0.11.1/specs/phase0/beacon-chain.md#bls-signatures
|
2020-03-04 21:27:11 +00:00
|
|
|
func blsVerify*(
|
|
|
|
pubkey: ValidatorPubKey, message: openArray[byte],
|
|
|
|
signature: ValidatorSig): bool =
|
|
|
|
## Check that a signature is valid for a message
|
|
|
|
## under the provided public key.
|
|
|
|
## returns `true` if the signature is valid, `false` otherwise.
|
|
|
|
##
|
|
|
|
## The proof-of-possession MUST be verified before calling this function.
|
|
|
|
## It is recommended to use the overload that accepts a proof-of-possession
|
|
|
|
## to enforce correct usage.
|
|
|
|
if signature.kind != Real:
|
|
|
|
# Invalid signatures are possible in deposits (discussed with Danny)
|
|
|
|
return false
|
|
|
|
if pubkey.kind != Real:
|
|
|
|
# TODO: chronicles warning
|
|
|
|
return false
|
2019-07-03 07:35:05 +00:00
|
|
|
|
2020-03-04 21:27:11 +00:00
|
|
|
# TODO: remove fully if the comment below is not true anymore and
|
|
|
|
# and we don't need this workaround
|
|
|
|
# # TODO bls_verify_multiple(...) used to have this workaround, and now it
|
|
|
|
# # lives here. No matter the signature, there's also no meaningful way to
|
|
|
|
# # verify it -- it's a kind of vacuous truth. No pubkey/sig pairs. Sans a
|
|
|
|
# # getBytes() or similar mechanism, pubKey == default(ValidatorPubKey) is
|
|
|
|
# # a way to create many false positive matches. This seems odd.
|
|
|
|
# if pubkey.getBytes() == default(ValidatorPubKey).getBytes():
|
|
|
|
# return true
|
|
|
|
pubkey.blsValue.verify(message, signature.blsValue)
|
|
|
|
|
|
|
|
func blsSign*(privkey: ValidatorPrivKey, message: openarray[byte]): ValidatorSig =
|
|
|
|
## Computes a signature from a secret key and a message
|
2020-04-11 08:51:07 +00:00
|
|
|
ValidatorSig(kind: Real, blsValue: SecretKey(privkey).sign(message))
|
2020-03-04 21:27:11 +00:00
|
|
|
|
|
|
|
func blsFastAggregateVerify*[T: byte|char](
|
|
|
|
publicKeys: openarray[ValidatorPubKey],
|
|
|
|
message: openarray[T],
|
|
|
|
signature: ValidatorSig
|
|
|
|
): bool =
|
|
|
|
## Verify the aggregate of multiple signatures on the same message
|
|
|
|
## This function is faster than AggregateVerify
|
|
|
|
##
|
|
|
|
## The proof-of-possession MUST be verified before calling this function.
|
|
|
|
## It is recommended to use the overload that accepts a proof-of-possession
|
|
|
|
## to enforce correct usage.
|
|
|
|
# TODO: Note: `invalid` in the following paragraph means invalid by construction
|
|
|
|
# The keys/signatures are not even points on the elliptic curves.
|
|
|
|
# To respect both the IETF API and the fact that
|
|
|
|
# we can have invalid public keys (as in not point on the elliptic curve),
|
|
|
|
# requiring a wrapper indirection,
|
|
|
|
# we need a first pass to extract keys from the wrapper
|
|
|
|
# and then call fastAggregateVerify.
|
|
|
|
# Instead:
|
|
|
|
# - either we expose a new API: context + init-update-finish
|
|
|
|
# in blscurve which already exists internally
|
|
|
|
# - or at network/databases/serialization boundaries we do not
|
|
|
|
# allow invalid BLS objects to pollute consensus routines
|
|
|
|
if signature.kind != Real:
|
|
|
|
return false
|
|
|
|
var unwrapped: seq[PublicKey]
|
|
|
|
for pubkey in publicKeys:
|
|
|
|
if pubkey.kind != Real:
|
|
|
|
return false
|
|
|
|
unwrapped.add pubkey.blsValue
|
|
|
|
return fastAggregateVerify(unwrapped, message, signature.blsValue)
|
2019-09-10 22:03:06 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
proc newKeyPair*(): BlsResult[tuple[pub: ValidatorPubKey, priv: ValidatorPrivKey]] =
|
2020-03-04 21:27:11 +00:00
|
|
|
## Generates a new public-private keypair
|
|
|
|
## This requires entropy on the system
|
|
|
|
# The input-keying-material requires 32 bytes at least for security
|
|
|
|
# The generation is deterministic and the input-keying-material
|
|
|
|
# must be protected against side-channel attacks
|
2019-12-06 12:05:00 +00:00
|
|
|
|
2020-03-04 21:27:11 +00:00
|
|
|
var ikm: array[32, byte]
|
2020-04-11 08:51:07 +00:00
|
|
|
if randomBytes(ikm) != 32:
|
|
|
|
return err "bls: no random bytes"
|
|
|
|
|
|
|
|
var
|
|
|
|
sk: SecretKey
|
|
|
|
pk: PublicKey
|
|
|
|
if keyGen(ikm, pk, sk):
|
|
|
|
ok((ValidatorPubKey(kind: Real, blsValue: pk), ValidatorPrivKey(sk)))
|
2020-03-19 16:18:48 +00:00
|
|
|
else:
|
2020-04-11 08:51:07 +00:00
|
|
|
err "bls: cannot generate keypair"
|
2019-12-06 12:05:00 +00:00
|
|
|
|
2020-03-04 21:27:11 +00:00
|
|
|
proc toGaugeValue*(hash: Eth2Digest): int64 =
|
|
|
|
# Only the last 8 bytes are taken into consideration in accordance
|
|
|
|
# to the ETH2 metrics spec:
|
|
|
|
# https://github.com/ethereum/eth2.0-metrics/blob/6a79914cb31f7d54858c7dd57eee75b6162ec737/metrics.md#interop-metrics
|
|
|
|
cast[int64](uint64.fromBytesLE(hash.data[24..31]))
|
|
|
|
|
|
|
|
# Codecs
|
|
|
|
# ----------------------------------------------------------------------
|
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
func `$`*(x: ValidatorPrivKey): string =
|
|
|
|
"<private key>"
|
|
|
|
|
2020-03-04 21:27:11 +00:00
|
|
|
func `$`*(x: BlsValue): string =
|
2020-03-11 13:50:08 +00:00
|
|
|
# The prefix must be short
|
|
|
|
# due to the mechanics of the `shortLog` function.
|
2020-03-04 21:27:11 +00:00
|
|
|
if x.kind == Real:
|
2020-03-19 16:18:48 +00:00
|
|
|
x.blsValue.toHex()
|
2019-07-03 07:35:05 +00:00
|
|
|
else:
|
2020-04-11 08:51:07 +00:00
|
|
|
"raw: " & x.blob.toHex()
|
2020-03-04 21:27:11 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
func toRaw*(x: ValidatorPrivKey): array[RawPrivKeySize, byte] =
|
|
|
|
SecretKey(x).exportRaw()
|
|
|
|
|
|
|
|
func toRaw*(x: BlsValue): auto =
|
2020-03-04 21:27:11 +00:00
|
|
|
if x.kind == Real:
|
|
|
|
x.blsValue.exportRaw()
|
|
|
|
else:
|
|
|
|
x.blob
|
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
func toHex*(x: BlsCurveType): string =
|
|
|
|
toHex(toRaw(x))
|
|
|
|
|
|
|
|
func fromRaw*(T: type ValidatorPrivKey, bytes: openarray[byte]): BlsResult[T] =
|
|
|
|
var val: SecretKey
|
|
|
|
if val.fromBytes(bytes):
|
|
|
|
ok ValidatorPrivKey(val)
|
|
|
|
else:
|
|
|
|
err "bls: invalid private key"
|
|
|
|
|
|
|
|
func fromRaw*[N, T](BT: type BlsValue[N, T], bytes: openarray[byte]): BlsResult[BT] =
|
2019-09-05 14:27:28 +00:00
|
|
|
# This is a workaround, so that we can deserialize the serialization of a
|
|
|
|
# default-initialized BlsValue without raising an exception
|
2019-09-05 19:52:34 +00:00
|
|
|
when defined(ssz_testing):
|
2019-09-09 03:33:24 +00:00
|
|
|
# Only for SSZ parsing tests, everything is an opaque blob
|
2020-04-11 08:51:07 +00:00
|
|
|
ok BT(kind: OpaqueBlob, blob: toArray(N, bytes))
|
2019-07-03 07:35:05 +00:00
|
|
|
else:
|
2019-09-09 03:33:24 +00:00
|
|
|
# Try if valid BLS value
|
2020-04-11 08:51:07 +00:00
|
|
|
var val: T
|
|
|
|
if fromBytes(val, bytes):
|
|
|
|
ok BT(kind: Real, blsValue: val)
|
|
|
|
else:
|
|
|
|
ok BT(kind: OpaqueBlob, blob: toArray(N, bytes))
|
2019-07-03 07:35:05 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
func fromHex*(T: type BlsCurveType, hexStr: string): BlsResult[T] {.inline.} =
|
2020-03-04 21:27:11 +00:00
|
|
|
## Initialize a BLSValue from its hex representation
|
2020-04-11 08:51:07 +00:00
|
|
|
try:
|
|
|
|
T.fromRaw(hexStr.hexToSeqByte())
|
|
|
|
except ValueError:
|
|
|
|
err "bls: cannot parse value"
|
2019-10-01 13:44:38 +00:00
|
|
|
|
2020-03-04 21:27:11 +00:00
|
|
|
# Hashing
|
|
|
|
# ----------------------------------------------------------------------
|
|
|
|
|
|
|
|
template hash*(x: BlsCurveType): Hash =
|
|
|
|
# TODO: prevent using secret keys
|
2020-04-11 08:51:07 +00:00
|
|
|
bind toRaw
|
|
|
|
hash(toRaw(x))
|
2020-03-04 21:27:11 +00:00
|
|
|
|
|
|
|
# Serialization
|
|
|
|
# ----------------------------------------------------------------------
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
proc writeValue*(writer: var JsonWriter, value: ValidatorPubKey) {.
|
|
|
|
inline, raises: [IOError, Defect].} =
|
2020-03-12 01:11:48 +00:00
|
|
|
writer.writeValue(value.toHex())
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
proc readValue*(reader: var JsonReader, value: var ValidatorPubKey) {.
|
|
|
|
inline, raises: [Exception].} =
|
|
|
|
value = ValidatorPubKey.fromHex(reader.readValue(string)).tryGet()
|
2018-12-19 12:58:53 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
proc writeValue*(writer: var JsonWriter, value: ValidatorSig) {.
|
|
|
|
inline, raises: [IOError, Defect].} =
|
|
|
|
# Workaround: https://github.com/status-im/nim-beacon-chain/issues/374
|
2020-03-12 01:11:48 +00:00
|
|
|
writer.writeValue(value.toHex())
|
2019-08-07 03:09:26 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
proc readValue*(reader: var JsonReader, value: var ValidatorSig) {.
|
|
|
|
inline, raises: [Exception].} =
|
|
|
|
value = ValidatorSig.fromHex(reader.readValue(string)).tryGet()
|
2019-08-07 03:09:26 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
proc writeValue*(writer: var JsonWriter, value: ValidatorPrivKey) {.
|
|
|
|
inline, raises: [IOError, Defect].} =
|
2020-03-12 01:11:48 +00:00
|
|
|
writer.writeValue(value.toHex())
|
2019-08-07 03:09:26 +00:00
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
proc readValue*(reader: var JsonReader, value: var ValidatorPrivKey) {.
|
|
|
|
inline, raises: [Exception].} =
|
|
|
|
value = ValidatorPrivKey.fromHex(reader.readValue(string)).tryGet()
|
2019-11-09 10:46:34 +00:00
|
|
|
|
|
|
|
template fromSszBytes*(T: type BlsValue, bytes: openarray[byte]): auto =
|
2020-04-11 08:51:07 +00:00
|
|
|
let v = fromRaw(T, bytes)
|
|
|
|
if v.isErr:
|
|
|
|
raise newException(MalformedSszError, $v.error)
|
|
|
|
v[]
|
|
|
|
|
|
|
|
# Logging
|
|
|
|
# ----------------------------------------------------------------------
|
|
|
|
|
|
|
|
func shortLog*(x: BlsValue): string =
|
|
|
|
## Logging for wrapped BLS types
|
|
|
|
## that may contain valid or non-validated data
|
|
|
|
# The prefix must be short
|
|
|
|
# due to the mechanics of the `shortLog` function.
|
|
|
|
if x.kind == Real:
|
|
|
|
x.blsValue.exportRaw()[0..3].toHex()
|
|
|
|
else:
|
|
|
|
"raw: " & x.blob[0..3].toHex()
|
|
|
|
|
|
|
|
func shortLog*(x: ValidatorPrivKey): string =
|
|
|
|
## Logging for raw unwrapped BLS types
|
|
|
|
x.toRaw()[0..3].toHex()
|
2020-03-04 21:27:11 +00:00
|
|
|
|
2020-03-04 22:13:37 +00:00
|
|
|
# Initialization
|
|
|
|
# ----------------------------------------------------------------------
|
|
|
|
|
2020-04-11 08:51:07 +00:00
|
|
|
# TODO more specific exceptions? don't raise?
|
|
|
|
|
2020-03-04 21:27:11 +00:00
|
|
|
# For confutils
|
2020-04-11 08:51:07 +00:00
|
|
|
func init*(T: typedesc[ValidatorPrivKey], hex: string): T {.noInit, raises: [ValueError, Defect].} =
|
|
|
|
let v = T.fromHex(hex)
|
|
|
|
if v.isErr:
|
|
|
|
raise (ref ValueError)(msg: $v.error)
|
|
|
|
return v[]
|
|
|
|
|
2020-03-04 22:13:37 +00:00
|
|
|
|
|
|
|
# For mainchain monitor
|
2020-04-11 08:51:07 +00:00
|
|
|
func init*(T: typedesc[ValidatorPubKey], data: array[RawPubKeySize, byte]): T {.noInit, raises: [ValueError, Defect].} =
|
|
|
|
let v = T.fromRaw(data)
|
|
|
|
if v.isErr:
|
|
|
|
raise (ref ValueError)(msg: $v.error)
|
|
|
|
return v[]
|
2020-03-04 22:41:21 +00:00
|
|
|
|
|
|
|
# For mainchain monitor
|
2020-04-11 08:51:07 +00:00
|
|
|
func init*(T: typedesc[ValidatorSig], data: array[RawSigSize, byte]): T {.noInit, raises: [ValueError, Defect].} =
|
|
|
|
let v = T.fromRaw(data)
|
|
|
|
if v.isErr:
|
|
|
|
raise (ref ValueError)(msg: $v.error)
|
|
|
|
return v[]
|