Skip to content

Commit

Permalink
[ETCM-522][ETCM-523] Apply scalafix and scalafmt
Browse files Browse the repository at this point in the history
  • Loading branch information
dzajkowski committed Jul 1, 2021
1 parent 661ac8b commit eb07b45
Show file tree
Hide file tree
Showing 607 changed files with 9,666 additions and 8,054 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ object ByteStringUtils {
ByteString(Hex.decode(hash))

implicit class Padding(val bs: ByteString) extends AnyVal {
def padToByteString(length: Int, b: Byte): ByteString = {
def padToByteString(length: Int, b: Byte): ByteString =
if (length <= bs.length) bs
else {
val len = Math.max(bs.length, length)
Expand All @@ -27,7 +27,6 @@ object ByteStringUtils {
}
ByteString.fromArray(result)
}
}
}

implicit class ByteStringOps(val bytes: ByteString) extends AnyVal {
Expand All @@ -54,9 +53,8 @@ object ByteStringUtils {
def asByteArray: Array[Byte] = Array(b)
}

implicit val byteStringOrdering: Ordering[ByteString] = {
implicit val byteStringOrdering: Ordering[ByteString] =
Ordering.by[ByteString, Seq[Byte]](_.toSeq)
}

def concatByteStrings(head: ByteStringElement, tail: ByteStringElement*): ByteString = {
val it = Iterator.single(head) ++ tail.iterator
Expand Down
32 changes: 12 additions & 20 deletions bytes/src/main/scala/io/iohk/ethereum/utils/ByteUtils.scala
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package io.iohk.ethereum.utils

import java.math.BigInteger
import java.nio.{ByteBuffer, ByteOrder}
import java.nio.ByteBuffer
import java.nio.ByteOrder

import akka.util.ByteString

import scala.util.Random

object ByteUtils {

/**
* Calculates number of matching bytes from the beginning of both arrays.
/** Calculates number of matching bytes from the beginning of both arrays.
* Due to performance reasons needs to be as fast as possible which means usage of while loops and var's.
*
* @param a - first array of bytes to check
Expand All @@ -19,9 +19,8 @@ object ByteUtils {
*/
def matchingLength(a: Array[Byte], b: Array[Byte]): Int = {
var prefixLen = 0
while (prefixLen < a.length && prefixLen < b.length && a(prefixLen) == b(prefixLen)) {
while (prefixLen < a.length && prefixLen < b.length && a(prefixLen) == b(prefixLen))
prefixLen = prefixLen + 1
}
prefixLen
}

Expand All @@ -38,16 +37,15 @@ object ByteUtils {
bigIntegerToBytes(b.bigInteger, numBytes)

def toBigInt(bytes: ByteString): BigInt =
bytes.foldLeft(BigInt(0)) { (n, b) => (n << 8) + (b & 0xff) }
bytes.foldLeft(BigInt(0))((n, b) => (n << 8) + (b & 0xff))

def bigIntToUnsignedByteArray(i: BigInt): Array[Byte] = {
val asByteArray = i.toByteArray
if (asByteArray.head == 0) asByteArray.tail
else asByteArray
}

/**
* Calculates xor distance between two byte arrays. Due to performance reasons needs to be as fast as possible
/** Calculates xor distance between two byte arrays. Due to performance reasons needs to be as fast as possible
* which means usage of while loops and var's.
*
* @param a - array of bytes to xor
Expand Down Expand Up @@ -108,9 +106,8 @@ object ByteUtils {
data
}

def compactPickledBytes(buffer: ByteBuffer): ByteString = {
def compactPickledBytes(buffer: ByteBuffer): ByteString =
ByteString(compactPickledBytesToArray(buffer))
}

def byteSequenceToBuffer(bytes: IndexedSeq[Byte]): ByteBuffer =
ByteBuffer.wrap(bytes.toArray)
Expand All @@ -127,12 +124,10 @@ object ByteUtils {
ret
}

def getIntFromWord(arr: Array[Byte]): Int = {
def getIntFromWord(arr: Array[Byte]): Int =
ByteBuffer.wrap(arr, 0, 4).order(ByteOrder.LITTLE_ENDIAN).getInt
}

/**
* Converts array of Int to corresponding array of bytes. Due to performance reasons needs to be as fast as possible
/** Converts array of Int to corresponding array of bytes. Due to performance reasons needs to be as fast as possible
* which means usage of while loops and var's.
*
* @param arr - array of int's to convert
Expand All @@ -141,7 +136,7 @@ object ByteUtils {
* @param bigEndian - param specifying which int representation should be used.
* @return Unit
*/
def intsToBytesMut(arr: Array[Int], b: Array[Byte], bigEndian: Boolean): Unit = {
def intsToBytesMut(arr: Array[Int], b: Array[Byte], bigEndian: Boolean): Unit =
if (!bigEndian) {
var off = 0
var i = 0
Expand Down Expand Up @@ -175,10 +170,8 @@ object ByteUtils {
i = i + 1
}
}
}

/**
* Converts array of bytes to corresponding array of ints. Due to performance reasons needs to be as fast as possible
/** Converts array of bytes to corresponding array of ints. Due to performance reasons needs to be as fast as possible
* which means usage of while loops and var's.
*
* @param b - array of bytes to convert
Expand All @@ -187,7 +180,7 @@ object ByteUtils {
* @param bigEndian - param specifying which int representation should be used.
* @return Unit
*/
def bytesToIntsMut(b: Array[Byte], arr: Array[Int], bigEndian: Boolean): Unit = {
def bytesToIntsMut(b: Array[Byte], arr: Array[Int], bigEndian: Boolean): Unit =
if (!bigEndian) {
var off = 0
var i = 0
Expand Down Expand Up @@ -222,6 +215,5 @@ object ByteUtils {
i = i + 1
}
}
}

}
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package io.iohk.ethereum.utils

import akka.util.ByteString
import org.scalatest.wordspec.AnyWordSpec

import scala.collection.immutable.ArraySeq
import scala.util.Failure
import scala.util.Success
import scala.util.Try

import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

import ByteStringUtils._
import scala.collection.immutable.ArraySeq
import scala.util.{Try, Success, Failure}

class ByteStringUtilsTest extends AnyWordSpec with Matchers {

Expand Down Expand Up @@ -39,7 +44,7 @@ class ByteStringUtilsTest extends AnyWordSpec with Matchers {
val bs3: Byte = 2
val bs4 = Array[Byte](3, 3)
val bs5 = Array[Byte](4, 4)
val summarized: ByteString = bs1 ++ bs2
bs1 ++ bs2
val concatenated: ByteString = ByteStringUtils.concatByteStrings(bs1, bs2, bs3, bs4, bs5)
concatenated shouldEqual string2hash("0000FFFF0203030404")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package io.iohk.ethereum.utils

import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalacheck.Arbitrary
import org.scalacheck.Gen
import org.scalatest.funsuite.AnyFunSuite
import org.scalacheck.{Arbitrary, Gen}
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class ByteUtilsSpec extends AnyFunSuite with ScalaCheckPropertyChecks {
def byteArrayOfNItemsGen(n: Int): Gen[Array[Byte]] =
Expand All @@ -12,15 +13,15 @@ class ByteUtilsSpec extends AnyFunSuite with ScalaCheckPropertyChecks {
forAll(byteArrayOfNItemsGen(32)) { bytes =>
val toInts = ByteUtils.bytesToInts(bytes, bigEndian = false)
val asBytes = ByteUtils.intsToBytes(toInts, bigEndian = false)
assert(asBytes sameElements bytes)
assert(asBytes.sameElements(bytes))
}
}

test("Convert Bytes to Int in big endian") {
forAll(byteArrayOfNItemsGen(32)) { bytes =>
val toInts = ByteUtils.bytesToInts(bytes, bigEndian = true)
val asBytes = ByteUtils.intsToBytes(toInts, bigEndian = true)
assert(asBytes sameElements bytes)
assert(asBytes.sameElements(bytes))
}
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
package io.iohk.ethereum.crypto

import akka.util.ByteString

import org.bouncycastle.crypto.Digest
import org.bouncycastle.util.Pack

/**
* Basic KDF generator for derived keys and ivs as defined by NIST SP 800-56A.
/** Basic KDF generator for derived keys and ivs as defined by NIST SP 800-56A.
* @param digest for source of derived keys
*/
class ConcatKDFBytesGenerator(digest: Digest) {
val digestSize: Int = digest.getDigestSize

/**
* @param outputLength length of output that will be produced by this method,
/** @param outputLength length of output that will be produced by this method,
* maximum value is (digest output size in bits) * (2^32 - 1) but it should not be a problem
* because we are using Int
* @throws scala.IllegalArgumentException ("Output length too large") when outputLength is greater than (digest output size in bits) * (2^32 - 1)
Expand Down
42 changes: 19 additions & 23 deletions crypto/src/main/scala/io/iohk/ethereum/crypto/ECDSASignature.scala
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package io.iohk.ethereum.crypto

import akka.util.ByteString
import io.iohk.ethereum.utils.ByteUtils

import scala.util.Try

import org.bouncycastle.asn1.x9.X9IntegerConverter
import org.bouncycastle.crypto.AsymmetricCipherKeyPair
import org.bouncycastle.crypto.digests.SHA256Digest
import org.bouncycastle.crypto.params.ECPublicKeyParameters
import org.bouncycastle.crypto.signers.{ECDSASigner, HMacDSAKCalculator}
import org.bouncycastle.math.ec.{ECCurve, ECPoint}
import org.bouncycastle.crypto.signers.ECDSASigner
import org.bouncycastle.crypto.signers.HMacDSAKCalculator
import org.bouncycastle.math.ec.ECCurve
import org.bouncycastle.math.ec.ECPoint

import scala.util.Try
import io.iohk.ethereum.utils.ByteUtils

object ECDSASignature {

Expand All @@ -29,18 +33,16 @@ object ECDSASignature {
val positivePointSign: Byte = 28
val newPositivePointSign: Byte = 36

val allowedPointSigns = Set(negativePointSign, positivePointSign)
val allowedPointSigns: Set[Byte] = Set(negativePointSign, positivePointSign)

def apply(r: ByteString, s: ByteString, v: Byte): ECDSASignature = {
def apply(r: ByteString, s: ByteString, v: Byte): ECDSASignature =
ECDSASignature(BigInt(1, r.toArray), BigInt(1, s.toArray), v)
}

def fromBytes(bytes65: ByteString): Option[ECDSASignature] = {
def fromBytes(bytes65: ByteString): Option[ECDSASignature] =
if (bytes65.length == EncodedLength)
Some(apply(bytes65.take(RLength), bytes65.drop(RLength).take(SLength), bytes65.last))
else
None
}

def sign(messageHash: ByteString, prvKey: ByteString): ECDSASignature =
sign(messageHash.toArray, keyPairFromPrvKey(prvKey.toArray), None)
Expand All @@ -63,18 +65,17 @@ object ECDSASignature {
val pointSign = chainId match {
case Some(id) if v == negativePointSign => (id * 2 + newNegativePointSign).toByte
case Some(id) if v == positivePointSign => (id * 2 + newPositivePointSign).toByte
case None => v
case _ => throw new IllegalStateException(s"Unexpected pointSign. ChainId: ${chainId}, v: ${v}")
case None => v
case _ => throw new IllegalStateException(s"Unexpected pointSign. ChainId: ${chainId}, v: ${v}")
}

ECDSASignature(r, s, pointSign)
}

/**
* new formula for calculating point sign post EIP 155 adoption
/** new formula for calculating point sign post EIP 155 adoption
* v = CHAIN_ID * 2 + 35 or v = CHAIN_ID * 2 + 36
*/
private def getRecoveredPointSign(pointSign: Byte, chainId: Option[Byte]): Option[Byte] = {
private def getRecoveredPointSign(pointSign: Byte, chainId: Option[Byte]): Option[Byte] =
(chainId match {
case Some(id) =>
if (pointSign == negativePointSign || pointSign == (id * 2 + newNegativePointSign).toByte) {
Expand All @@ -86,7 +87,6 @@ object ECDSASignature {
}
case None => Some(pointSign)
}).filter(pointSign => allowedPointSigns.contains(pointSign))
}

private def canonicalise(s: BigInt): BigInt = {
val halfCurveOrder: BigInt = curveParams.getN.shiftRight(1)
Expand All @@ -109,7 +109,7 @@ object ECDSASignature {
recId: Byte,
chainId: Option[Byte],
messageHash: Array[Byte]
): Option[Array[Byte]] = {
): Option[Array[Byte]] =
Try {
val order = curve.getCurve.getOrder
//ignore case when x = r + order because it is negligibly improbable
Expand All @@ -132,7 +132,6 @@ object ECDSASignature {
} else None
}
}.toOption.flatten
}

private def constructPoint(xCoordinate: BigInt, recId: Int): ECPoint = {
val x9 = new X9IntegerConverter
Expand All @@ -142,8 +141,7 @@ object ECDSASignature {
}
}

/**
* ECDSASignature r and s are same as in documentation where signature is represented by tuple (r, s)
/** ECDSASignature r and s are same as in documentation where signature is represented by tuple (r, s)
*
* The `publicKey` method is also the way to verify the signature: if the key can be retrieved based
* on the signed message, the signature is correct, otherwise it isn't.
Expand All @@ -154,17 +152,15 @@ object ECDSASignature {
*/
case class ECDSASignature(r: BigInt, s: BigInt, v: Byte) {

/**
* returns ECC point encoded with on compression and without leading byte indicating compression
/** returns ECC point encoded with on compression and without leading byte indicating compression
* @param messageHash message to be signed; should be a hash of the actual data.
* @param chainId optional value if you want new signing schema with recovery id calculated with chain id
* @return
*/
def publicKey(messageHash: Array[Byte], chainId: Option[Byte] = None): Option[Array[Byte]] =
ECDSASignature.recoverPubBytes(r, s, v, chainId, messageHash)

/**
* returns ECC point encoded with on compression and without leading byte indicating compression
/** returns ECC point encoded with on compression and without leading byte indicating compression
* @param messageHash message to be signed; should be a hash of the actual data.
* @return
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
package io.iohk.ethereum.crypto

import java.io.{ByteArrayInputStream, IOException}
import java.io.ByteArrayInputStream
import java.io.IOException
import java.math.BigInteger
import java.security.SecureRandom

import org.bouncycastle.crypto.BufferedBlockCipher
import org.bouncycastle.crypto.InvalidCipherTextException
import org.bouncycastle.crypto.digests.SHA256Digest
import org.bouncycastle.crypto.engines.AESEngine
import org.bouncycastle.crypto.generators.ECKeyPairGenerator
import org.bouncycastle.crypto.macs.HMac
import org.bouncycastle.crypto.modes.SICBlockCipher
import org.bouncycastle.crypto.params._
import org.bouncycastle.crypto.{BufferedBlockCipher, InvalidCipherTextException}
import org.bouncycastle.math.ec.ECPoint

object ECIESCoder {

val KeySize = 128
val PublicKeyOverheadSize = 65
val MacOverheadSize = 32
val OverheadSize = PublicKeyOverheadSize + KeySize / 8 + MacOverheadSize
val OverheadSize: Int = PublicKeyOverheadSize + KeySize / 8 + MacOverheadSize

@throws[IOException]
@throws[InvalidCipherTextException]
Expand Down
Loading

0 comments on commit eb07b45

Please sign in to comment.