-
Notifications
You must be signed in to change notification settings - Fork 75
ETCM-167: Scalanet Discovery part 3 #766
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 all commits
Commits
Show all changes
36 commits
Select commit
Hold shift + click to select a range
edc01e2
ETCM-167: Testing skeleton for EIP8 test vectors.
aakoshh 3e70ca2
ETCM-167: An RLP codec for Ping.
aakoshh 060ee45
ETCM-167: Generic derivation of RLPEncoder for case classes.
aakoshh 0f3244e
ETCM-167: Add FieldInfo to know we're in a trailing position.
aakoshh 0ad0440
ETCM-167: Require a derivation policy to enable the omission of trail…
aakoshh a5e3494
ETCM-167: Generic derivation of decoder.
aakoshh 9ae6647
ETCM-167: Combine encoder and decoder into codec.
aakoshh aae3ff3
ETCM-167: Auto-derive RLP for Node.Address.
aakoshh ea44306
ETCM-167: RLP codec for all payloads.
aakoshh 077965e
ETCM-167: Codec for Payload.
aakoshh 69e7d6b
ETCM-167: Testing the RLP codecs on the EIP8 test vectors.
a3e77e4
ETCM-167: Test EIP8 with Mantis discovery messages and fix the new co…
aakoshh 70f57a9
ETCM-167: Default derivation policy.
aakoshh 552056d
ETCM-167: Test that we encode to the same bits.
aakoshh 1894fa8
ETCM-167: Preserve the innermost encodeable in errors.
aakoshh 5ebf7c5
ETCM-167: Testing the SigAlg methods.
aakoshh 95a2b4b
ETCM-167: Use the Keccak256 hash on the data before signing.
aakoshh 732e5e7
ETCM-167: Try both possible recovery IDs when the signature doesn't h…
aakoshh b706ece
ETCM-167: Decompress public key using formulas.
aakoshh 1f5dfdb
ETCM-167: Decompress using bouncycastle.
aakoshh 0f848d9
ETCM-167: Decompress public key during verification.
aakoshh cc8e8bb
ETCM-167: Enable RLP tests that needed crypto.
aakoshh 71494ac
ETCM-167: Moved tests to separate files.
aakoshh c211b9e
ETCM-167: Testing the ENR codecs.
aakoshh 66190f4
ETCM-167: Sanity check on the example node ID.
aakoshh 8623bac
ETCM-167: Flattened the crypto package to avoid shadowing.
aakoshh a257570
ETCM-167: Patched repo.nix
aakoshh ed5a782
ETCM-167: Added PacketType to hold bytes to keep scalafmt happy.
aakoshh 747adde
ETCM-167: Fix hash docs.
aakoshh 5a73ad7
ETCM-167: Fix EVM test to sign a hash.
aakoshh ac06b41
ETCM-167: Use +: instead of :: on RLPList.
aakoshh c3fb180
ETCM-167: Compress / uncompress with Bouncy castle ECPublicKeyParamet…
aakoshh 9cdab08
ETCM-167: Rename to messageHash
aakoshh 8a3447f
ETCM-167: Cache the signing key pair.
aakoshh 199e05d
ETCM-167: Added example encodings for each payload type.
aakoshh 0ee0cbe
ETCM-167: Use the same examples for decoding as well.
aakoshh 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
Large diffs are not rendered by default.
Oops, something went wrong.
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
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
186 changes: 186 additions & 0 deletions
186
src/main/scala/io/iohk/ethereum/network/discovery/Secp256k1SigAlg.scala
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,186 @@ | ||
package io.iohk.ethereum.network.discovery | ||
|
||
import akka.util.ByteString | ||
import io.iohk.ethereum.crypto | ||
import io.iohk.ethereum.crypto.ECDSASignature | ||
import io.iohk.scalanet.discovery.crypto.{SigAlg, PublicKey, PrivateKey, Signature} | ||
import io.iohk.ethereum.nodebuilder.SecureRandomBuilder | ||
import scodec.bits.BitVector | ||
import scodec.{Attempt, Err} | ||
import scodec.bits.BitVector | ||
import org.bouncycastle.crypto.params.ECPublicKeyParameters | ||
import org.bouncycastle.crypto.AsymmetricCipherKeyPair | ||
import scala.collection.concurrent.TrieMap | ||
|
||
class Secp256k1SigAlg extends SigAlg with SecureRandomBuilder { | ||
// We'll be using the same private key over and over to sign messages. | ||
// To save the time transforming it into a public-private key pair every time, store the results. | ||
// In the future we might want to not pass around the private key but have it as a constructor argument. | ||
private val signingKeyPairCache = TrieMap.empty[PrivateKey, AsymmetricCipherKeyPair] | ||
|
||
override val name = "secp256k1" | ||
|
||
override val PrivateKeyBytesSize = 32 | ||
|
||
// A Secp256k1 public key is 32 bytes compressed or 64 bytes uncompressed, | ||
// with a 1 byte prefix showing which version it is. | ||
// See https://davidederosa.com/basic-blockchain-programming/elliptic-curve-keys | ||
// | ||
// However in the discovery v4 protocol the prefix is omitted. | ||
override val PublicKeyBytesSize = 64 | ||
|
||
// A normal Secp256k1 signature consists of 2 bigints `r` and `s` followed by a recovery ID `v`, | ||
// but it can be just 64 bytes if that's omitted, like in the ENR. | ||
override val SignatureBytesSize = 65 | ||
|
||
val SignatureWithoutRecoveryBytesSize = 64 | ||
val PublicKeyCompressedBytesSize = 33 | ||
|
||
override def newKeyPair: (PublicKey, PrivateKey) = { | ||
val keyPair = crypto.generateKeyPair(secureRandom) | ||
val (privateKeyBytes, publicKeyBytes) = crypto.keyPairToByteArrays(keyPair) | ||
|
||
val publicKey = toPublicKey(publicKeyBytes) | ||
val privateKey = toPrivateKey(privateKeyBytes) | ||
|
||
publicKey -> privateKey | ||
} | ||
|
||
override def sign(privateKey: PrivateKey, data: BitVector): Signature = { | ||
val message = crypto.kec256(data.toByteArray) | ||
val keyPair = signingKeyPairCache.getOrElseUpdate(privateKey, crypto.keyPairFromPrvKey(privateKey.toByteArray)) | ||
val sig = ECDSASignature.sign(message, keyPair) | ||
toSignature(sig) | ||
} | ||
|
||
// ENR wants the signature without recovery ID, just 64 bytes. | ||
// The Packet on the other hand has the full 65 bytes. | ||
override def removeRecoveryId(signature: Signature): Signature = { | ||
signature.size / 8 match { | ||
case SignatureBytesSize => | ||
Signature(signature.dropRight(8)) | ||
case SignatureWithoutRecoveryBytesSize => | ||
signature | ||
case other => | ||
throw new IllegalArgumentException(s"Unexpected signature size: $other bytes") | ||
} | ||
} | ||
|
||
override def compressPublicKey(publicKey: PublicKey): PublicKey = { | ||
publicKey.size / 8 match { | ||
case PublicKeyBytesSize => | ||
// This is a public key without the prefix, it consists of an x and y bigint. | ||
// To compress we drop y, and the first byte becomes 02 for even values of y and 03 for odd values. | ||
val point = crypto.curve.getCurve.decodePoint(ECDSASignature.UncompressedIndicator +: publicKey.toByteArray) | ||
val key = new ECPublicKeyParameters(point, crypto.curve) | ||
val bytes = key.getQ.getEncoded(true) // compressed encoding | ||
val compressed = PublicKey(BitVector(bytes)) | ||
assert(compressed.size == PublicKeyCompressedBytesSize * 8) | ||
compressed | ||
|
||
case PublicKeyCompressedBytesSize => | ||
publicKey | ||
|
||
case other => | ||
throw new IllegalArgumentException(s"Unexpected uncompressed public key size: $other bytes") | ||
} | ||
} | ||
|
||
// The public key points lie on the curve `y^2 = x^3 + 7`. | ||
// In the compressed form we have x and a prefix telling us whether y is even or odd. | ||
// https://bitcoin.stackexchange.com/questions/86234/how-to-uncompress-a-public-key | ||
// https://bitcoin.stackexchange.com/questions/44024/get-uncompressed-public-key-from-compressed-form | ||
def decompressPublicKey(publicKey: PublicKey): PublicKey = { | ||
publicKey.size / 8 match { | ||
case PublicKeyBytesSize => | ||
publicKey | ||
|
||
case PublicKeyCompressedBytesSize => | ||
val point = crypto.curve.getCurve.decodePoint(publicKey.toByteArray) | ||
aakoshh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
val key = new ECPublicKeyParameters(point, crypto.curve) | ||
val bytes = key.getQ.getEncoded(false).drop(1) // uncompressed encoding, drop prefix. | ||
toPublicKey(bytes) | ||
|
||
case other => | ||
throw new IllegalArgumentException(s"Unexpected compressed public key size: $other bytes") | ||
} | ||
} | ||
|
||
override def verify(publicKey: PublicKey, signature: Signature, data: BitVector): Boolean = { | ||
val message = crypto.kec256(data.toByteArray) | ||
val uncompressedPublicKey = decompressPublicKey(publicKey) | ||
toECDSASignatures(signature).exists { sig => | ||
sig.publicKey(message).map(toPublicKey).contains(uncompressedPublicKey) | ||
} | ||
} | ||
|
||
override def recoverPublicKey(signature: Signature, data: BitVector): Attempt[PublicKey] = { | ||
val message = crypto.kec256(data.toByteArray) | ||
|
||
val maybePublicKey = toECDSASignatures(signature).flatMap { sig => | ||
sig.publicKey(message).map(toPublicKey) | ||
}.headOption | ||
|
||
Attempt.fromOption(maybePublicKey, Err("Failed to recover the public key from the signature.")) | ||
} | ||
|
||
override def toPublicKey(privateKey: PrivateKey): PublicKey = { | ||
val publicKeyBytes = crypto.pubKeyFromPrvKey(privateKey.toByteArray) | ||
toPublicKey(publicKeyBytes) | ||
} | ||
|
||
private def toPublicKey(publicKeyBytes: Array[Byte]): PublicKey = { | ||
// Discovery uses 64 byte keys, without the prefix. | ||
val publicKey = PublicKey(BitVector(publicKeyBytes)) | ||
assert(publicKey.size == PublicKeyBytesSize * 8, s"Unexpected public key size: ${publicKey.size / 8} bytes") | ||
publicKey | ||
} | ||
|
||
private def toPrivateKey(privateKeyBytes: Array[Byte]): PrivateKey = { | ||
val privateKey = PrivateKey(BitVector(privateKeyBytes)) | ||
assert(privateKey.size == PrivateKeyBytesSize * 8, s"Unexpected private key size: ${privateKey.size / 8} bytes") | ||
privateKey | ||
} | ||
|
||
// Apparently the `v` has to adjusted by 27, which is the negative point sign. | ||
private def vToWire(v: Byte): Byte = | ||
(v - ECDSASignature.negativePointSign).toByte | ||
|
||
private def wireToV(w: Byte): Byte = | ||
(w + ECDSASignature.negativePointSign).toByte | ||
|
||
private def adjustV(bytes: Array[Byte], f: Byte => Byte): Unit = | ||
bytes(bytes.size - 1) = f(bytes(bytes.size - 1)) | ||
|
||
private def toSignature(sig: ECDSASignature): Signature = { | ||
val signatureBytes = sig.toBytes.toArray[Byte] | ||
assert(signatureBytes.size == SignatureBytesSize) | ||
adjustV(signatureBytes, vToWire) | ||
Signature(BitVector(signatureBytes)) | ||
} | ||
|
||
// Based on whether we have the recovery ID in the signature we may have to try 1 or 2 signatures. | ||
private def toECDSASignatures(signature: Signature): Iterable[ECDSASignature] = { | ||
signature.size / 8 match { | ||
case SignatureBytesSize => | ||
val signatureBytes = signature.toByteArray | ||
adjustV(signatureBytes, wireToV) | ||
Iterable(toECDSASignature(signatureBytes)) | ||
|
||
case SignatureWithoutRecoveryBytesSize => | ||
val signatureBytes = signature.toByteArray | ||
// Try all allowed points signs. | ||
ECDSASignature.allowedPointSigns.toIterable.map { v => | ||
toECDSASignature(signatureBytes :+ v) | ||
} | ||
|
||
case other => | ||
throw new IllegalArgumentException(s"Unexpected signature size: $other bytes") | ||
} | ||
} | ||
|
||
private def toECDSASignature(signatureBytes: Array[Byte]): ECDSASignature = | ||
ECDSASignature.fromBytes(ByteString(signatureBytes)) getOrElse { | ||
throw new IllegalArgumentException(s"Could not convert to ECDSA signature.") | ||
} | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This one randomly returned 32 or 33 bytes.