Skip to content

Commit

Permalink
Add parenthesis to randomXXX functions
Browse files Browse the repository at this point in the history
These functions have side-effects, it was incorrect and misleading to expose
them without parenthesis.
  • Loading branch information
t-bast committed May 17, 2021
1 parent ce7a12d commit 1e9f0ce
Show file tree
Hide file tree
Showing 73 changed files with 716 additions and 717 deletions.
2 changes: 1 addition & 1 deletion eclair-core/src/main/scala/fr/acinq/eclair/Eclair.scala
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ trait Eclair {

def sendBlocking(externalId_opt: Option[String], recipientNodeId: PublicKey, amount: MilliSatoshi, paymentHash: ByteVector32, invoice_opt: Option[PaymentRequest] = None, maxAttempts_opt: Option[Int] = None, feeThresholdSat_opt: Option[Satoshi] = None, maxFeePct_opt: Option[Double] = None)(implicit timeout: Timeout): Future[Either[PreimageReceived, PaymentEvent]]

def sendWithPreimage(externalId_opt: Option[String], recipientNodeId: PublicKey, amount: MilliSatoshi, paymentPreimage: ByteVector32 = randomBytes32, maxAttempts_opt: Option[Int] = None, feeThresholdSat_opt: Option[Satoshi] = None, maxFeePct_opt: Option[Double] = None)(implicit timeout: Timeout): Future[UUID]
def sendWithPreimage(externalId_opt: Option[String], recipientNodeId: PublicKey, amount: MilliSatoshi, paymentPreimage: ByteVector32 = randomBytes32(), maxAttempts_opt: Option[Int] = None, feeThresholdSat_opt: Option[Satoshi] = None, maxFeePct_opt: Option[Double] = None)(implicit timeout: Timeout): Future[UUID]

def sentInfo(id: Either[UUID, ByteVector32])(implicit timeout: Timeout): Future[Seq[OutgoingPayment]]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ object NodeParams extends Logging {
migrateSeedFile(oldSeedPath, seedPath)
readSeedFromFile(seedPath)
} else {
val randomSeed = randomBytes32
val randomSeed = randomBytes32()
writeSeedToFile(seedPath, randomSeed)
randomSeed.bytes
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ class Channel(val nodeParams: NodeParams, val wallet: EclairWallet, remoteNodeId
LocalChanges(Nil, Nil, Nil), RemoteChanges(Nil, Nil, Nil),
localNextHtlcId = 0L, remoteNextHtlcId = 0L,
originChannels = Map.empty,
remoteNextCommitInfo = Right(randomKey.publicKey), // we will receive their next per-commitment point in the next message, so we temporarily put a random byte array,
remoteNextCommitInfo = Right(randomKey().publicKey), // we will receive their next per-commitment point in the next message, so we temporarily put a random byte array,
commitInput, ShaChain.init, channelId = channelId)
peer ! ChannelIdAssigned(self, remoteNodeId, temporaryChannelId, channelId) // we notify the peer asap so it knows how to route messages
txPublisher ! SetChannelId(remoteNodeId, channelId)
Expand Down Expand Up @@ -534,7 +534,7 @@ class Channel(val nodeParams: NodeParams, val wallet: EclairWallet, remoteNodeId
LocalChanges(Nil, Nil, Nil), RemoteChanges(Nil, Nil, Nil),
localNextHtlcId = 0L, remoteNextHtlcId = 0L,
originChannels = Map.empty,
remoteNextCommitInfo = Right(randomKey.publicKey), // we will receive their next per-commitment point in the next message, so we temporarily put a random byte array
remoteNextCommitInfo = Right(randomKey().publicKey), // we will receive their next per-commitment point in the next message, so we temporarily put a random byte array
commitInput, ShaChain.init, channelId = channelId)
val now = System.currentTimeMillis.milliseconds.toSeconds
context.system.eventStream.publish(ChannelSignatureReceived(self, commitments))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class LocalChannelKeyManager(seed: ByteVector, chainHash: ByteVector32) extends
override def newFundingKeyPath(isFunder: Boolean): KeyPath = {
val last = DeterministicWallet.hardened(if (isFunder) 1 else 0)

def next(): Long = randomLong & 0xFFFFFFFFL
def next(): Long = randomLong() & 0xFFFFFFFFL

DeterministicWallet.KeyPath(Seq(next(), next(), next(), next(), next(), next(), next(), next(), last))
}
Expand Down
2 changes: 1 addition & 1 deletion eclair-core/src/main/scala/fr/acinq/eclair/io/Peer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class Peer(val nodeParams: NodeParams, remoteNodeId: PublicKey, wallet: EclairWa
val channelVersion = ChannelVersion.pickChannelVersion(d.localFeatures, d.remoteFeatures)
val (channel, localParams) = createNewChannel(nodeParams, d.localFeatures, funder = true, c.fundingSatoshis, origin_opt = Some(sender), channelVersion)
c.timeout_opt.map(openTimeout => context.system.scheduler.scheduleOnce(openTimeout.duration, channel, Channel.TickChannelOpenTimeout)(context.dispatcher))
val temporaryChannelId = randomBytes32
val temporaryChannelId = randomBytes32()
val channelFeeratePerKw = nodeParams.onChainFeeConf.getCommitmentFeerate(remoteNodeId, channelVersion, c.fundingSatoshis, None)
val fundingTxFeeratePerKw = c.fundingTxFeeratePerKw_opt.getOrElse(nodeParams.onChainFeeConf.feeEstimator.getFeeratePerKw(target = nodeParams.onChainFeeConf.feeTargets.fundingBlockTarget))
log.info(s"requesting a new channel with fundingSatoshis=${c.fundingSatoshis}, pushMsat=${c.pushMsat} and fundingFeeratePerByte=${c.fundingTxFeeratePerKw_opt} temporaryChannelId=$temporaryChannelId localParams=$localParams")
Expand Down
8 changes: 4 additions & 4 deletions eclair-core/src/main/scala/fr/acinq/eclair/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ package object eclair {
ByteVector.view(buffer)
}

def randomBytes32: ByteVector32 = ByteVector32(randomBytes(32))
def randomBytes32(): ByteVector32 = ByteVector32(randomBytes(32))

def randomBytes64: ByteVector64 = ByteVector64(randomBytes(64))
def randomBytes64(): ByteVector64 = ByteVector64(randomBytes(64))

def randomKey: PrivateKey = PrivateKey(randomBytes32)
def randomKey(): PrivateKey = PrivateKey(randomBytes32())

def randomLong: Long = randomGen.nextLong()
def randomLong(): Long = randomGen.nextLong()

def toLongId(fundingTxHash: ByteVector32, fundingOutputIndex: Int): ByteVector32 = {
require(fundingOutputIndex < 65536, "fundingOutputIndex must not be greater than FFFF")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ object OutgoingPacket {
*/
def buildOnion[T <: Onion.PacketType](packetType: Sphinx.OnionRoutingPacket[T])(nodes: Seq[PublicKey], payloads: Seq[Onion.PerHopPayload], associatedData: ByteVector32): Sphinx.PacketAndSecrets = {
require(nodes.size == payloads.size)
val sessionKey = randomKey
val sessionKey = randomKey()
val payloadsBin: Seq[ByteVector] = payloads
.map {
case p: Onion.FinalPayload => OnionCodecs.finalPerHopPayloadCodec.encode(p)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ object PaymentRequest {
expirySeconds.map(Expiry(_)),
Some(MinFinalCltvExpiry(minFinalCltvExpiryDelta.toInt)),
features).flatten
val paymentSecretTag = if (features.exists(_.allowPaymentSecret)) PaymentSecret(randomBytes32) :: Nil else Nil
val paymentSecretTag = if (features.exists(_.allowPaymentSecret)) PaymentSecret(randomBytes32()) :: Nil else Nil
val routingInfoTags = extraHops.map(RoutingInfo)
defaultTags ++ paymentSecretTag ++ routingInfoTags
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class MultiPartHandler(nodeParams: NodeParams, register: ActorRef, db: IncomingP
override def handle(implicit ctx: ActorContext, log: DiagnosticLoggingAdapter): Receive = {
case ReceivePayment(amount_opt, desc, expirySeconds_opt, extraHops, fallbackAddress_opt, paymentPreimage_opt, paymentType) =>
Try {
val paymentPreimage = paymentPreimage_opt.getOrElse(randomBytes32)
val paymentPreimage = paymentPreimage_opt.getOrElse(randomBytes32())
val paymentHash = Crypto.sha256(paymentPreimage)
val expirySeconds = expirySeconds_opt.getOrElse(nodeParams.paymentRequestExpiry.toSeconds)
// We currently only optionally support payment secrets (to allow legacy clients to pay invoices).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ class NodeRelay private(nodeParams: NodeParams,
case None =>
context.log.debug("sending the payment to the next trampoline node")
val payFSM = outgoingPaymentFactory.spawnOutgoingPayFSM(context, paymentCfg, multiPart = true)
val paymentSecret = randomBytes32 // we generate a new secret to protect against probing attacks
val paymentSecret = randomBytes32() // we generate a new secret to protect against probing attacks
val payment = SendMultiPartPayment(payFsmAdapters, paymentSecret, payloadOut.outgoingNodeId, payloadOut.amountToForward, payloadOut.outgoingCltv, nodeParams.maxPaymentAttempts, routeParams = Some(routeParams), additionalTlvs = Seq(OnionTlv.TrampolineOnion(packetOut)))
payFSM ! payment
payFSM
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class Autoprobe(nodeParams: NodeParams, router: ActorRef, paymentInitiator: Acto
case TickProbe =>
pickPaymentDestination(nodeParams.nodeId, routingData) match {
case Some(targetNodeId) =>
val paymentHash = randomBytes32 // we don't even know the preimage (this needs to be a secure random!)
val paymentHash = randomBytes32() // we don't even know the preimage (this needs to be a secure random!)
log.info(s"sending payment probe to node=$targetNodeId payment_hash=$paymentHash")
paymentInitiator ! PaymentInitiator.SendPaymentRequest(PAYMENT_AMOUNT_MSAT, paymentHash, targetNodeId, maxAttempts = 1)
case None =>
Expand Down Expand Up @@ -96,7 +96,7 @@ object Autoprobe {
if (peers.isEmpty) {
None
} else {
peers.drop(randomLong.toInt % peers.size).headOption
peers.drop(randomLong().toInt % peers.size).headOption
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ class PaymentInitiator(nodeParams: NodeParams, outgoingPaymentFactory: PaymentIn
case trampoline :: recipient :: Nil =>
log.info(s"sending trampoline payment to $recipient with trampoline=$trampoline, trampoline fees=${r.trampolineFees}, expiry delta=${r.trampolineExpiryDelta}")
// We generate a random secret for the payment to the first trampoline node.
val trampolineSecret = r.trampolineSecret.getOrElse(randomBytes32)
val trampolineSecret = r.trampolineSecret.getOrElse(randomBytes32())
sender ! SendPaymentToRouteResponse(paymentId, parentPaymentId, Some(trampolineSecret))
val (trampolineAmount, trampolineExpiry, trampolineOnion) = buildTrampolinePayment(SendTrampolinePaymentRequest(r.recipientAmount, r.paymentRequest, trampoline, Seq((r.trampolineFees, r.trampolineExpiryDelta)), r.fallbackFinalExpiryDelta), r.trampolineFees, r.trampolineExpiryDelta)
payFsm ! SendPaymentToRoute(sender, Left(r.route), Onion.createMultiPartPayload(r.amount, trampolineAmount, trampolineExpiry, trampolineSecret, Seq(OnionTlv.TrampolineOnion(trampolineOnion))), r.paymentRequest.routingInfo)
Expand Down Expand Up @@ -169,7 +169,7 @@ class PaymentInitiator(nodeParams: NodeParams, outgoingPaymentFactory: PaymentIn
private def sendTrampolinePayment(paymentId: UUID, r: SendTrampolinePaymentRequest, trampolineFees: MilliSatoshi, trampolineExpiryDelta: CltvExpiryDelta): Unit = {
val paymentCfg = SendPaymentConfig(paymentId, paymentId, None, r.paymentHash, r.recipientAmount, r.recipientNodeId, Upstream.Local(paymentId), Some(r.paymentRequest), storeInDb = true, publishEvent = false, Seq(NodeHop(r.trampolineNodeId, r.recipientNodeId, trampolineExpiryDelta, trampolineFees)))
// We generate a random secret for this payment to avoid leaking the invoice secret to the first trampoline node.
val trampolineSecret = randomBytes32
val trampolineSecret = randomBytes32()
val (trampolineAmount, trampolineExpiry, trampolineOnion) = buildTrampolinePayment(r, trampolineFees, trampolineExpiryDelta)
val fsm = outgoingPaymentFactory.spawnOutgoingMultiPartPayment(context, paymentCfg)
fsm ! SendMultiPartPayment(self, trampolineSecret, r.trampolineNodeId, trampolineAmount, trampolineExpiry, 1, r.paymentRequest.routingInfo, r.routeParams, Seq(OnionTlv.TrampolineOnion(trampolineOnion)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,8 @@ object TorProtocolHandler {

// @formatter:off
sealed trait Authentication
case class Password(password: String) extends Authentication { override def toString = "password" }
case class SafeCookie(nonce: ByteVector = fr.acinq.eclair.randomBytes32) extends Authentication { override def toString = "safecookie" }
case class Password(password: String) extends Authentication { override def toString = "password" }
case class SafeCookie(nonce: ByteVector = fr.acinq.eclair.randomBytes32()) extends Authentication { override def toString = "safecookie" }
// @formatter:on

object Authentication {
Expand Down
26 changes: 13 additions & 13 deletions eclair-core/src/test/scala/fr/acinq/eclair/EclairImplSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ class EclairImplSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike with I
// with assisted routes
val externalId1 = "030bb6a5e0c6b203c7e2180fb78c7ba4bdce46126761d8201b91ddac089cdecc87"
val hints = List(List(ExtraHop(Bob.nodeParams.nodeId, ShortChannelId("569178x2331x1"), feeBase = 10 msat, feeProportionalMillionths = 1, cltvExpiryDelta = CltvExpiryDelta(12))))
val invoice1 = PaymentRequest(Block.RegtestGenesisBlock.hash, Some(123 msat), ByteVector32.Zeroes, randomKey, "description", CltvExpiryDelta(18), None, None, hints)
val invoice1 = PaymentRequest(Block.RegtestGenesisBlock.hash, Some(123 msat), ByteVector32.Zeroes, randomKey(), "description", CltvExpiryDelta(18), None, None, hints)
eclair.send(Some(externalId1), nodeId, 123 msat, ByteVector32.Zeroes, invoice_opt = Some(invoice1))
val send1 = paymentInitiator.expectMsgType[SendPaymentRequest]
assert(send1.externalId === Some(externalId1))
Expand Down Expand Up @@ -156,13 +156,13 @@ class EclairImplSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike with I
import f._

val eclair = new EclairImpl(kit)
val remoteNodeAnn1 = NodeAnnouncement(randomBytes64, Features.empty, 42L, randomKey.publicKey, Color(42, 42, 42), "LN-rocks", Nil)
val remoteNodeAnn2 = NodeAnnouncement(randomBytes64, Features.empty, 43L, randomKey.publicKey, Color(43, 43, 43), "LN-papers", Nil)
val remoteNodeAnn1 = NodeAnnouncement(randomBytes64(), Features.empty, 42L, randomKey().publicKey, Color(42, 42, 42), "LN-rocks", Nil)
val remoteNodeAnn2 = NodeAnnouncement(randomBytes64(), Features.empty, 43L, randomKey().publicKey, Color(43, 43, 43), "LN-papers", Nil)
val allNodes = Seq(
NodeAnnouncement(randomBytes64, Features.empty, 561L, randomKey.publicKey, Color(0, 0, 0), "some-node", Nil),
NodeAnnouncement(randomBytes64(), Features.empty, 561L, randomKey().publicKey, Color(0, 0, 0), "some-node", Nil),
remoteNodeAnn1,
remoteNodeAnn2,
NodeAnnouncement(randomBytes64, Features.empty, 1105L, randomKey.publicKey, Color(0, 0, 0), "some-other-node", Nil),
NodeAnnouncement(randomBytes64(), Features.empty, 1105L, randomKey().publicKey, Color(0, 0, 0), "some-other-node", Nil),
)

{
Expand All @@ -188,7 +188,7 @@ class EclairImplSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike with I
})
}
{
val fRes = eclair.nodes(Some(Set(randomKey.publicKey)))
val fRes = eclair.nodes(Some(Set(randomKey().publicKey)))
router.expectMsg(Router.GetNodes)
router.reply(allNodes)
awaitCond(fRes.value match {
Expand Down Expand Up @@ -332,7 +332,7 @@ class EclairImplSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike with I

val kitWithPaymentHandler = kit.copy(paymentHandler = system.actorOf(PaymentHandler.props(Alice.nodeParams, TestProbe().ref)))
val eclair = new EclairImpl(kitWithPaymentHandler)
val paymentPreimage = randomBytes32
val paymentPreimage = randomBytes32()

val fResp = eclair.receive("some desc", None, None, None, Some(paymentPreimage))
awaitCond({
Expand Down Expand Up @@ -378,11 +378,11 @@ class EclairImplSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike with I
import f._

val eclair = new EclairImpl(kit)
val route = PredefinedNodeRoute(Seq(randomKey.publicKey))
val trampolines = Seq(randomKey.publicKey, randomKey.publicKey)
val route = PredefinedNodeRoute(Seq(randomKey().publicKey))
val trampolines = Seq(randomKey().publicKey, randomKey().publicKey)
val parentId = UUID.randomUUID()
val secret = randomBytes32
val pr = PaymentRequest(Block.LivenetGenesisBlock.hash, Some(1234 msat), ByteVector32.One, randomKey, "Some invoice", CltvExpiryDelta(18))
val secret = randomBytes32()
val pr = PaymentRequest(Block.LivenetGenesisBlock.hash, Some(1234 msat), ByteVector32.One, randomKey(), "Some invoice", CltvExpiryDelta(18))
eclair.sendToRoute(1000 msat, Some(1200 msat), Some("42"), Some(parentId), pr, CltvExpiryDelta(123), route, Some(secret), Some(100 msat), Some(CltvExpiryDelta(144)), trampolines)

paymentInitiator.expectMsg(SendPaymentToRouteRequest(1000 msat, 1200 msat, Some("42"), Some(parentId), pr, CltvExpiryDelta(123), route, Some(secret), 100 msat, CltvExpiryDelta(144), trampolines))
Expand All @@ -392,7 +392,7 @@ class EclairImplSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike with I
import f._

val eclair = new EclairImpl(kit)
val nodeId = randomKey.publicKey
val nodeId = randomKey().publicKey

eclair.sendWithPreimage(None, nodeId, 12345 msat)
val send = paymentInitiator.expectMsgType[SendPaymentRequest]
Expand All @@ -412,7 +412,7 @@ class EclairImplSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike with I
import f._

val eclair = new EclairImpl(kit)
val nodeId = randomKey.publicKey
val nodeId = randomKey().publicKey
val expectedPaymentPreimage = ByteVector32(hex"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")
val expectedPaymentHash = Crypto.sha256(expectedPaymentPreimage)

Expand Down
4 changes: 2 additions & 2 deletions eclair-core/src/test/scala/fr/acinq/eclair/StartupSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ class StartupSpec extends AnyFunSuite {

def makeNodeParamsWithDefaults(conf: Config): NodeParams = {
val blockCount = new AtomicLong(0)
val nodeKeyManager = new LocalNodeKeyManager(randomBytes32, chainHash = Block.TestnetGenesisBlock.hash)
val channelKeyManager = new LocalChannelKeyManager(randomBytes32, chainHash = Block.TestnetGenesisBlock.hash)
val nodeKeyManager = new LocalNodeKeyManager(randomBytes32(), chainHash = Block.TestnetGenesisBlock.hash)
val channelKeyManager = new LocalChannelKeyManager(randomBytes32(), chainHash = Block.TestnetGenesisBlock.hash)
val feeEstimator = new TestConstants.TestFeeEstimator
val db = TestDatabases.inMemoryDb()
NodeParams.makeNodeParams(conf, UUID.fromString("01234567-0123-4567-89ab-0123456789ab"), nodeKeyManager, channelKeyManager, None, db, blockCount, feeEstimator)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

package fr.acinq.eclair

import fr.acinq.bitcoin.Crypto.PrivateKey
import fr.acinq.bitcoin.{Block, ByteVector32, Satoshi, SatoshiLong, Script}
import fr.acinq.eclair.FeatureSupport.Optional
import fr.acinq.eclair.Features._
Expand Down Expand Up @@ -169,7 +168,7 @@ object TestConstants {
def channelParams: LocalParams = Peer.makeChannelParams(
nodeParams,
nodeParams.features,
Script.write(Script.pay2wpkh(PrivateKey(randomBytes32).publicKey)),
Script.write(Script.pay2wpkh(randomKey().publicKey)),
None,
isFunder = true,
fundingSatoshis
Expand Down Expand Up @@ -273,7 +272,7 @@ object TestConstants {
def channelParams: LocalParams = Peer.makeChannelParams(
nodeParams,
nodeParams.features,
Script.write(Script.pay2wpkh(PrivateKey(randomBytes32).publicKey)),
Script.write(Script.pay2wpkh(randomKey().publicKey)),
None,
isFunder = false,
fundingSatoshis).copy(
Expand Down
Loading

0 comments on commit 1e9f0ce

Please sign in to comment.