|
| 1 | +package io.iohk.ethereum.network.discovery |
| 2 | + |
| 3 | +import akka.util.ByteString |
| 4 | +import io.iohk.ethereum.crypto |
| 5 | +import io.iohk.ethereum.crypto.ECDSASignature |
| 6 | +import io.iohk.scalanet.discovery.crypto.{SigAlg, PublicKey, PrivateKey, Signature} |
| 7 | +import io.iohk.ethereum.nodebuilder.SecureRandomBuilder |
| 8 | +import scodec.bits.BitVector |
| 9 | +import scodec.{Attempt, Err} |
| 10 | +import scodec.bits.BitVector |
| 11 | +import org.bouncycastle.crypto.params.ECPublicKeyParameters |
| 12 | +import org.bouncycastle.crypto.AsymmetricCipherKeyPair |
| 13 | +import scala.collection.concurrent.TrieMap |
| 14 | + |
| 15 | +class Secp256k1SigAlg extends SigAlg with SecureRandomBuilder { |
| 16 | + // We'll be using the same private key over and over to sign messages. |
| 17 | + // To save the time transforming it into a public-private key pair every time, store the results. |
| 18 | + // In the future we might want to not pass around the private key but have it as a constructor argument. |
| 19 | + private val signingKeyPairCache = TrieMap.empty[PrivateKey, AsymmetricCipherKeyPair] |
| 20 | + |
| 21 | + override val name = "secp256k1" |
| 22 | + |
| 23 | + override val PrivateKeyBytesSize = 32 |
| 24 | + |
| 25 | + // A Secp256k1 public key is 32 bytes compressed or 64 bytes uncompressed, |
| 26 | + // with a 1 byte prefix showing which version it is. |
| 27 | + // See https://davidederosa.com/basic-blockchain-programming/elliptic-curve-keys |
| 28 | + // |
| 29 | + // However in the discovery v4 protocol the prefix is omitted. |
| 30 | + override val PublicKeyBytesSize = 64 |
| 31 | + |
| 32 | + // A normal Secp256k1 signature consists of 2 bigints `r` and `s` followed by a recovery ID `v`, |
| 33 | + // but it can be just 64 bytes if that's omitted, like in the ENR. |
| 34 | + override val SignatureBytesSize = 65 |
| 35 | + |
| 36 | + val SignatureWithoutRecoveryBytesSize = 64 |
| 37 | + val PublicKeyCompressedBytesSize = 33 |
| 38 | + |
| 39 | + override def newKeyPair: (PublicKey, PrivateKey) = { |
| 40 | + val keyPair = crypto.generateKeyPair(secureRandom) |
| 41 | + val (privateKeyBytes, publicKeyBytes) = crypto.keyPairToByteArrays(keyPair) |
| 42 | + |
| 43 | + val publicKey = toPublicKey(publicKeyBytes) |
| 44 | + val privateKey = toPrivateKey(privateKeyBytes) |
| 45 | + |
| 46 | + publicKey -> privateKey |
| 47 | + } |
| 48 | + |
| 49 | + override def sign(privateKey: PrivateKey, data: BitVector): Signature = { |
| 50 | + val message = crypto.kec256(data.toByteArray) |
| 51 | + val keyPair = signingKeyPairCache.getOrElseUpdate(privateKey, crypto.keyPairFromPrvKey(privateKey.toByteArray)) |
| 52 | + val sig = ECDSASignature.sign(message, keyPair) |
| 53 | + toSignature(sig) |
| 54 | + } |
| 55 | + |
| 56 | + // ENR wants the signature without recovery ID, just 64 bytes. |
| 57 | + // The Packet on the other hand has the full 65 bytes. |
| 58 | + override def removeRecoveryId(signature: Signature): Signature = { |
| 59 | + signature.size / 8 match { |
| 60 | + case SignatureBytesSize => |
| 61 | + Signature(signature.dropRight(8)) |
| 62 | + case SignatureWithoutRecoveryBytesSize => |
| 63 | + signature |
| 64 | + case other => |
| 65 | + throw new IllegalArgumentException(s"Unexpected signature size: $other bytes") |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + override def compressPublicKey(publicKey: PublicKey): PublicKey = { |
| 70 | + publicKey.size / 8 match { |
| 71 | + case PublicKeyBytesSize => |
| 72 | + // This is a public key without the prefix, it consists of an x and y bigint. |
| 73 | + // To compress we drop y, and the first byte becomes 02 for even values of y and 03 for odd values. |
| 74 | + val point = crypto.curve.getCurve.decodePoint(ECDSASignature.UncompressedIndicator +: publicKey.toByteArray) |
| 75 | + val key = new ECPublicKeyParameters(point, crypto.curve) |
| 76 | + val bytes = key.getQ.getEncoded(true) // compressed encoding |
| 77 | + val compressed = PublicKey(BitVector(bytes)) |
| 78 | + assert(compressed.size == PublicKeyCompressedBytesSize * 8) |
| 79 | + compressed |
| 80 | + |
| 81 | + case PublicKeyCompressedBytesSize => |
| 82 | + publicKey |
| 83 | + |
| 84 | + case other => |
| 85 | + throw new IllegalArgumentException(s"Unexpected uncompressed public key size: $other bytes") |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + // The public key points lie on the curve `y^2 = x^3 + 7`. |
| 90 | + // In the compressed form we have x and a prefix telling us whether y is even or odd. |
| 91 | + // https://bitcoin.stackexchange.com/questions/86234/how-to-uncompress-a-public-key |
| 92 | + // https://bitcoin.stackexchange.com/questions/44024/get-uncompressed-public-key-from-compressed-form |
| 93 | + def decompressPublicKey(publicKey: PublicKey): PublicKey = { |
| 94 | + publicKey.size / 8 match { |
| 95 | + case PublicKeyBytesSize => |
| 96 | + publicKey |
| 97 | + |
| 98 | + case PublicKeyCompressedBytesSize => |
| 99 | + val point = crypto.curve.getCurve.decodePoint(publicKey.toByteArray) |
| 100 | + val key = new ECPublicKeyParameters(point, crypto.curve) |
| 101 | + val bytes = key.getQ.getEncoded(false).drop(1) // uncompressed encoding, drop prefix. |
| 102 | + toPublicKey(bytes) |
| 103 | + |
| 104 | + case other => |
| 105 | + throw new IllegalArgumentException(s"Unexpected compressed public key size: $other bytes") |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + override def verify(publicKey: PublicKey, signature: Signature, data: BitVector): Boolean = { |
| 110 | + val message = crypto.kec256(data.toByteArray) |
| 111 | + val uncompressedPublicKey = decompressPublicKey(publicKey) |
| 112 | + toECDSASignatures(signature).exists { sig => |
| 113 | + sig.publicKey(message).map(toPublicKey).contains(uncompressedPublicKey) |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + override def recoverPublicKey(signature: Signature, data: BitVector): Attempt[PublicKey] = { |
| 118 | + val message = crypto.kec256(data.toByteArray) |
| 119 | + |
| 120 | + val maybePublicKey = toECDSASignatures(signature).flatMap { sig => |
| 121 | + sig.publicKey(message).map(toPublicKey) |
| 122 | + }.headOption |
| 123 | + |
| 124 | + Attempt.fromOption(maybePublicKey, Err("Failed to recover the public key from the signature.")) |
| 125 | + } |
| 126 | + |
| 127 | + override def toPublicKey(privateKey: PrivateKey): PublicKey = { |
| 128 | + val publicKeyBytes = crypto.pubKeyFromPrvKey(privateKey.toByteArray) |
| 129 | + toPublicKey(publicKeyBytes) |
| 130 | + } |
| 131 | + |
| 132 | + private def toPublicKey(publicKeyBytes: Array[Byte]): PublicKey = { |
| 133 | + // Discovery uses 64 byte keys, without the prefix. |
| 134 | + val publicKey = PublicKey(BitVector(publicKeyBytes)) |
| 135 | + assert(publicKey.size == PublicKeyBytesSize * 8, s"Unexpected public key size: ${publicKey.size / 8} bytes") |
| 136 | + publicKey |
| 137 | + } |
| 138 | + |
| 139 | + private def toPrivateKey(privateKeyBytes: Array[Byte]): PrivateKey = { |
| 140 | + val privateKey = PrivateKey(BitVector(privateKeyBytes)) |
| 141 | + assert(privateKey.size == PrivateKeyBytesSize * 8, s"Unexpected private key size: ${privateKey.size / 8} bytes") |
| 142 | + privateKey |
| 143 | + } |
| 144 | + |
| 145 | + // Apparently the `v` has to adjusted by 27, which is the negative point sign. |
| 146 | + private def vToWire(v: Byte): Byte = |
| 147 | + (v - ECDSASignature.negativePointSign).toByte |
| 148 | + |
| 149 | + private def wireToV(w: Byte): Byte = |
| 150 | + (w + ECDSASignature.negativePointSign).toByte |
| 151 | + |
| 152 | + private def adjustV(bytes: Array[Byte], f: Byte => Byte): Unit = |
| 153 | + bytes(bytes.size - 1) = f(bytes(bytes.size - 1)) |
| 154 | + |
| 155 | + private def toSignature(sig: ECDSASignature): Signature = { |
| 156 | + val signatureBytes = sig.toBytes.toArray[Byte] |
| 157 | + assert(signatureBytes.size == SignatureBytesSize) |
| 158 | + adjustV(signatureBytes, vToWire) |
| 159 | + Signature(BitVector(signatureBytes)) |
| 160 | + } |
| 161 | + |
| 162 | + // Based on whether we have the recovery ID in the signature we may have to try 1 or 2 signatures. |
| 163 | + private def toECDSASignatures(signature: Signature): Iterable[ECDSASignature] = { |
| 164 | + signature.size / 8 match { |
| 165 | + case SignatureBytesSize => |
| 166 | + val signatureBytes = signature.toByteArray |
| 167 | + adjustV(signatureBytes, wireToV) |
| 168 | + Iterable(toECDSASignature(signatureBytes)) |
| 169 | + |
| 170 | + case SignatureWithoutRecoveryBytesSize => |
| 171 | + val signatureBytes = signature.toByteArray |
| 172 | + // Try all allowed points signs. |
| 173 | + ECDSASignature.allowedPointSigns.toIterable.map { v => |
| 174 | + toECDSASignature(signatureBytes :+ v) |
| 175 | + } |
| 176 | + |
| 177 | + case other => |
| 178 | + throw new IllegalArgumentException(s"Unexpected signature size: $other bytes") |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + private def toECDSASignature(signatureBytes: Array[Byte]): ECDSASignature = |
| 183 | + ECDSASignature.fromBytes(ByteString(signatureBytes)) getOrElse { |
| 184 | + throw new IllegalArgumentException(s"Could not convert to ECDSA signature.") |
| 185 | + } |
| 186 | +} |
0 commit comments