Spotless fixes.

This commit is contained in:
Vitor Pamplona
2024-01-06 10:44:32 -05:00
parent de61f7f383
commit ec867ae8a2
418 changed files with 74380 additions and 61924 deletions

View File

@@ -1,13 +1,31 @@
/**
* Copyright (c) 2023 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.benchmark
import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vitorpamplona.quartz.encoders.Bech32
import com.vitorpamplona.quartz.encoders.Hex
import com.vitorpamplona.quartz.encoders.bechToBytes
import com.vitorpamplona.quartz.encoders.toNpub
import com.vitorpamplona.quartz.events.Event
import junit.framework.TestCase.assertEquals
import org.junit.Rule
import org.junit.Test
@@ -15,25 +33,58 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class BechBenchmark {
@get:Rule val benchmarkRule = BenchmarkRule()
@get:Rule
val benchmarkRule = BenchmarkRule()
@Test
fun npubEncoding() {
val myUser = Hex.decode("460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c")
benchmarkRule.measureRepeated {
assertEquals("npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z",myUser.toNpub())
}
@Test
fun npubEncoding() {
val myUser = Hex.decode("460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c")
benchmarkRule.measureRepeated {
assertEquals(
"npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z",
myUser.toNpub(),
)
}
}
@Test
fun npubDecoding() {
val myUser = "npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z"
val expected = listOf(70, 12, 37, -26, -126, -3, -89, -125, 43, 82, -47, -14, 45, 61, 34, -77, 23, 109, -105, 47, 96, -36, -36, 50, 18, -19, -116, -110, -17, -123, 6, 92).map { it.toByte() }
benchmarkRule.measureRepeated {
assertEquals(expected, myUser.bechToBytes().toList())
}
}
}
@Test
fun npubDecoding() {
val myUser = "npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z"
val expected =
listOf(
70,
12,
37,
-26,
-126,
-3,
-89,
-125,
43,
82,
-47,
-14,
45,
61,
34,
-77,
23,
109,
-105,
47,
96,
-36,
-36,
50,
18,
-19,
-116,
-110,
-17,
-123,
6,
92,
)
.map { it.toByte() }
benchmarkRule.measureRepeated { assertEquals(expected, myUser.bechToBytes().toList()) }
}
}

View File

@@ -1,3 +1,23 @@
/**
* Copyright (c) 2023 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.benchmark
import androidx.benchmark.junit4.BenchmarkRule
@@ -5,7 +25,6 @@ import androidx.benchmark.junit4.measureRepeated
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vitorpamplona.quartz.utils.DualCase
import com.vitorpamplona.quartz.utils.containsAny
import com.vitorpamplona.quartz.utils.containsIgnoreCase
import junit.framework.TestCase.assertTrue
import org.junit.Rule
import org.junit.Test
@@ -13,85 +32,71 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ContainsBenchmark {
@get:Rule
val benchmarkRule = BenchmarkRule()
@get:Rule val benchmarkRule = BenchmarkRule()
private val test = """Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
private val test =
"""Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
""".intern()
"""
.intern()
val atTheMiddle = DualCase("Lorem Ipsum".lowercase(), "Lorem Ipsum".uppercase())
val atTheBeginning = DualCase("contrAry".lowercase(), "contrAry".uppercase())
val atTheMiddle = DualCase("Lorem Ipsum".lowercase(), "Lorem Ipsum".uppercase())
val atTheBeginning = DualCase("contrAry".lowercase(), "contrAry".uppercase())
val atTheEndCase = DualCase("h. rackham".lowercase(), "h. rackham".uppercase())
val atTheEndCase = DualCase("h. rackham".lowercase(), "h. rackham".uppercase())
val lastCase = listOf(
DualCase("my mom".lowercase(), "my mom".uppercase()),
DualCase("my dad".lowercase(), "my dad".uppercase()),
DualCase("h. rackham".lowercase(), "h. rackham".uppercase())
val lastCase =
listOf(
DualCase("my mom".lowercase(), "my mom".uppercase()),
DualCase("my dad".lowercase(), "my dad".uppercase()),
DualCase("h. rackham".lowercase(), "h. rackham".uppercase()),
)
@Test
fun middleCaseKotlin() {
benchmarkRule.measureRepeated {
assertTrue(test.contains(atTheMiddle.lowercase, true))
}
}
@Test
fun middleCaseKotlin() {
benchmarkRule.measureRepeated { assertTrue(test.contains(atTheMiddle.lowercase, true)) }
}
@Test
fun middleCaseOurs() {
val list = listOf(atTheMiddle)
benchmarkRule.measureRepeated {
assertTrue(test.containsAny(list))
}
}
@Test
fun middleCaseOurs() {
val list = listOf(atTheMiddle)
benchmarkRule.measureRepeated { assertTrue(test.containsAny(list)) }
}
@Test
fun atTheBeginningKotlin() {
benchmarkRule.measureRepeated {
assertTrue(test.contains(atTheBeginning.lowercase, true))
}
}
@Test
fun atTheBeginningKotlin() {
benchmarkRule.measureRepeated { assertTrue(test.contains(atTheBeginning.lowercase, true)) }
}
@Test
fun atTheBeginningOurs() {
val list = listOf(atTheBeginning)
benchmarkRule.measureRepeated {
assertTrue(test.containsAny(list))
}
}
@Test
fun atTheBeginningOurs() {
val list = listOf(atTheBeginning)
benchmarkRule.measureRepeated { assertTrue(test.containsAny(list)) }
}
@Test
fun atTheEndKotlin() {
benchmarkRule.measureRepeated {
assertTrue(test.contains(atTheEndCase.lowercase, true))
}
}
@Test
fun atTheEndKotlin() {
benchmarkRule.measureRepeated { assertTrue(test.contains(atTheEndCase.lowercase, true)) }
}
@Test
fun atTheEndOurs() {
val list = listOf(atTheEndCase)
benchmarkRule.measureRepeated {
assertTrue(test.containsAny(list))
}
}
@Test
fun atTheEndOurs() {
val list = listOf(atTheEndCase)
benchmarkRule.measureRepeated { assertTrue(test.containsAny(list)) }
}
@Test
fun theLastAtTheEndKotlin() {
benchmarkRule.measureRepeated {
assertTrue(
lastCase.any {
test.contains(it.lowercase, true)
}
)
}
@Test
fun theLastAtTheEndKotlin() {
benchmarkRule.measureRepeated {
assertTrue(
lastCase.any { test.contains(it.lowercase, true) },
)
}
}
@Test
fun theLastAtTheEndOurs() {
benchmarkRule.measureRepeated {
assertTrue(test.containsAny(lastCase))
}
}
}
@Test
fun theLastAtTheEndOurs() {
benchmarkRule.measureRepeated { assertTrue(test.containsAny(lastCase)) }
}
}

View File

@@ -1,3 +1,23 @@
/**
* Copyright (c) 2023 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.benchmark
import androidx.benchmark.junit4.BenchmarkRule
@@ -12,85 +32,76 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CryptoBenchmark {
@get:Rule val benchmarkRule = BenchmarkRule()
@get:Rule
val benchmarkRule = BenchmarkRule()
@Test
fun getSharedKeyNip04() {
val keyPair1 = KeyPair()
val keyPair2 = KeyPair()
@Test
fun getSharedKeyNip04() {
val keyPair1 = KeyPair()
val keyPair2 = KeyPair()
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.getSharedSecretNIP04(keyPair1.privKey!!, keyPair2.pubKey))
}
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.getSharedSecretNIP04(keyPair1.privKey!!, keyPair2.pubKey))
}
}
@Test
fun getSharedKeyNip44() {
val keyPair1 = KeyPair()
val keyPair2 = KeyPair()
@Test
fun getSharedKeyNip44() {
val keyPair1 = KeyPair()
val keyPair2 = KeyPair()
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.getSharedSecretNIP44v1(keyPair1.privKey!!, keyPair2.pubKey))
}
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.getSharedSecretNIP44v1(keyPair1.privKey!!, keyPair2.pubKey))
}
}
@Test
fun computeSharedKeyNip04() {
val keyPair1 = KeyPair()
val keyPair2 = KeyPair()
@Test
fun computeSharedKeyNip04() {
val keyPair1 = KeyPair()
val keyPair2 = KeyPair()
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.computeSharedSecretNIP04(keyPair1.privKey!!, keyPair2.pubKey))
}
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.computeSharedSecretNIP04(keyPair1.privKey!!, keyPair2.pubKey))
}
}
@Test
fun computeSharedKeyNip44() {
val keyPair1 = KeyPair()
val keyPair2 = KeyPair()
@Test
fun computeSharedKeyNip44() {
val keyPair1 = KeyPair()
val keyPair2 = KeyPair()
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.computeSharedSecretNIP44v1(keyPair1.privKey!!, keyPair2.pubKey))
}
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.computeSharedSecretNIP44v1(keyPair1.privKey!!, keyPair2.pubKey))
}
}
@Test
fun random() {
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.random(1000))
}
@Test
fun random() {
benchmarkRule.measureRepeated { assertNotNull(CryptoUtils.random(1000)) }
}
@Test
fun sha256() {
val keyPair = KeyPair()
benchmarkRule.measureRepeated { assertNotNull(CryptoUtils.sha256(keyPair.pubKey)) }
}
@Test
fun sign() {
val keyPair = KeyPair()
val msg = CryptoUtils.sha256(CryptoUtils.random(1000))
benchmarkRule.measureRepeated { assertNotNull(CryptoUtils.sign(msg, keyPair.privKey!!)) }
}
@Test
fun verify() {
val keyPair = KeyPair()
val msg = CryptoUtils.sha256(CryptoUtils.random(1000))
val signature = CryptoUtils.sign(msg, keyPair.privKey!!)
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.verifySignature(signature, msg, keyPair.pubKey))
}
@Test
fun sha256() {
val keyPair = KeyPair()
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.sha256(keyPair.pubKey))
}
}
@Test
fun sign() {
val keyPair = KeyPair()
val msg = CryptoUtils.sha256(CryptoUtils.random(1000))
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.sign(msg, keyPair.privKey!!))
}
}
@Test
fun verify() {
val keyPair = KeyPair()
val msg = CryptoUtils.sha256(CryptoUtils.random(1000))
val signature = CryptoUtils.sign(msg, keyPair.privKey!!)
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.verifySignature(signature, msg, keyPair.pubKey))
}
}
}
}
}

View File

@@ -1,3 +1,23 @@
/**
* Copyright (c) 2023 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.benchmark
import androidx.benchmark.junit4.BenchmarkRule
@@ -14,15 +34,16 @@ import org.junit.runner.RunWith
/**
* Benchmark, which will execute on an Android device.
*
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will
* output the result. Modify your code to see how it affects performance.
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will output the
* result. Modify your code to see how it affects performance.
*/
@RunWith(AndroidJUnit4::class)
class EventBenchmark {
val payload1 =
"[\"EVENT\",\"40b9\",{\"id\":\"48a72b485d38338627ec9d427583551f9af4f016c739b8ec0d6313540a8b12cf\",\"kind\":1,\"pubkey\":\"3d842afecd5e293f28b6627933704a3fb8ce153aa91d790ab11f6a752d44a42d\",\"created_at\":1677940007,\"content\":\"I got asked about follower count again today. Why does my follower count go down when I delete public relays (in our list) and replace them with filter.nostr.wine? \\n\\nIll give you one final explanation to rule them all. First, lets go over how clients calculate your follower count.\\n\\n1. Your client sends a request to all your connected relays asking for accounts who follow you\\n2. Relays answer back with the events requested\\n3. The client aggregates the event total and displays it\\n\\nEach relay has a set limit on how many stored events it will return per request. For some relays its 500, others 1000, some as high as 5000. Lets say for simplicity that all your public relays use 500 as their limit. If you ask 10 relays for your followers the max possible answer you can get is 5000. That wont change if you have 20,000 followers or 100,000. You may get back a “different” 5000 each time, but youll still cap out at 5000 because that is the most events your client will receive.\u2028\u2028Our limit on filter.nostr.wine is 2000 events. If you replace 10 public relays with only filter.nostr.wine, the MOST followers you will ever get back from our filter relay is 2000. That doesnt mean you only have 2000 followers or that your reach is reduced in any way.\\n\\nAs long as you are writing to and reading from the same public relays, neither your reach nor any content was lost. That concludes my TED talk. I hope you all have a fantastic day and weekend.\",\"tags\":[],\"sig\":\"dcaf8ab98bb9179017b35bd814092850d1062b26c263dff89fb1ae8c019a324139d1729012d9d05ff0a517f76b1117d869b2cc7d36bea8aa5f4b94c5e2548aa8\"}]"
val payload1 = "[\"EVENT\",\"40b9\",{\"id\":\"48a72b485d38338627ec9d427583551f9af4f016c739b8ec0d6313540a8b12cf\",\"kind\":1,\"pubkey\":\"3d842afecd5e293f28b6627933704a3fb8ce153aa91d790ab11f6a752d44a42d\",\"created_at\":1677940007,\"content\":\"I got asked about follower count again today. Why does my follower count go down when I delete public relays (in our list) and replace them with filter.nostr.wine? \\n\\nIll give you one final explanation to rule them all. First, lets go over how clients calculate your follower count.\\n\\n1. Your client sends a request to all your connected relays asking for accounts who follow you\\n2. Relays answer back with the events requested\\n3. The client aggregates the event total and displays it\\n\\nEach relay has a set limit on how many stored events it will return per request. For some relays its 500, others 1000, some as high as 5000. Lets say for simplicity that all your public relays use 500 as their limit. If you ask 10 relays for your followers the max possible answer you can get is 5000. That wont change if you have 20,000 followers or 100,000. You may get back a “different” 5000 each time, but youll still cap out at 5000 because that is the most events your client will receive.\u2028\u2028Our limit on filter.nostr.wine is 2000 events. If you replace 10 public relays with only filter.nostr.wine, the MOST followers you will ever get back from our filter relay is 2000. That doesnt mean you only have 2000 followers or that your reach is reduced in any way.\\n\\nAs long as you are writing to and reading from the same public relays, neither your reach nor any content was lost. That concludes my TED talk. I hope you all have a fantastic day and weekend.\",\"tags\":[],\"sig\":\"dcaf8ab98bb9179017b35bd814092850d1062b26c263dff89fb1ae8c019a324139d1729012d9d05ff0a517f76b1117d869b2cc7d36bea8aa5f4b94c5e2548aa8\"}]"
val payload2 = """
val payload2 =
"""
{
"content": "Astral:\n\nhttps://void.cat/d/A5Fba5B1bcxwEmeyoD9nBs.webp\n\nIris:\n\nhttps://void.cat/d/44hTcVvhRps6xYYs99QsqA.webp\n\nSnort:\n\nhttps://void.cat/d/4nJD5TRePuQChM5tzteYbU.webp\n\nAmethyst agrees with Astral which I suspect are both wrong. nostr:npub13sx6fp3pxq5rl70x0kyfmunyzaa9pzt5utltjm0p8xqyafndv95q3saapa nostr:npub1v0lxxxxutpvrelsksy8cdhgfux9l6a42hsj2qzquu2zk7vc9qnkszrqj49 nostr:npub1g53mukxnjkcmr94fhryzkqutdz2ukq4ks0gvy5af25rgmwsl4ngq43drvk nostr:npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z ",
"created_at": 1683596206,
@@ -49,74 +70,66 @@ class EventBenchmark {
}
"""
@get:Rule
val benchmarkRule = BenchmarkRule()
@get:Rule val benchmarkRule = BenchmarkRule()
@Test
fun parseREQString() {
benchmarkRule.measureRepeated {
Event.mapper.readTree(payload1)
}
@Test
fun parseREQString() {
benchmarkRule.measureRepeated { Event.mapper.readTree(payload1) }
}
@Test
fun parseEvent() {
val msg = Event.mapper.readTree(payload1)
benchmarkRule.measureRepeated { Event.fromJson(msg[2]) }
}
@Test
fun checkSignature() {
val msg = Event.mapper.readTree(payload1)
val event = Event.fromJson(msg[2])
benchmarkRule.measureRepeated {
// Should pass
assertTrue(event.hasVerifiedSignature())
}
}
@Test
fun parseEvent() {
val msg = Event.mapper.readTree(payload1)
@Test
fun checkIDHashPayload1() {
val msg = Event.mapper.readTree(payload1)
val event = Event.fromJson(msg[2])
benchmarkRule.measureRepeated {
Event.fromJson(msg[2])
}
benchmarkRule.measureRepeated {
// Should pass
assertTrue(event.hasCorrectIDHash())
}
}
@Test
fun checkSignature() {
val msg = Event.mapper.readTree(payload1)
val event = Event.fromJson(msg[2])
benchmarkRule.measureRepeated {
// Should pass
assertTrue( event.hasVerifiedSignature() )
}
@Test
fun checkIDHashPayload2() {
val event = Event.fromJson(payload2)
benchmarkRule.measureRepeated {
// Should pass
assertTrue(event.hasCorrectIDHash())
}
}
@Test
fun checkIDHashPayload1() {
val msg = Event.mapper.readTree(payload1)
val event = Event.fromJson(msg[2])
@Test
fun toMakeJsonForID() {
val event = Event.fromJson(payload2)
benchmarkRule.measureRepeated {
// Should pass
assertTrue( event.hasCorrectIDHash() )
}
benchmarkRule.measureRepeated { assertNotNull(event.makeJsonForId()) }
}
@Test
fun sha256() {
val event = Event.fromJson(payload2)
val byteArray = event.makeJsonForId().toByteArray()
benchmarkRule.measureRepeated {
// Should pass
assertNotNull(CryptoUtils.sha256(byteArray))
}
@Test
fun checkIDHashPayload2() {
val event = Event.fromJson(payload2)
benchmarkRule.measureRepeated {
// Should pass
assertTrue( event.hasCorrectIDHash() )
}
}
@Test
fun toMakeJsonForID() {
val event = Event.fromJson(payload2)
benchmarkRule.measureRepeated {
assertNotNull(event.makeJsonForId())
}
}
@Test
fun sha256() {
val event = Event.fromJson(payload2)
val byteArray = event.makeJsonForId().toByteArray()
benchmarkRule.measureRepeated {
// Should pass
assertNotNull(CryptoUtils.sha256(byteArray))
}
}
}
}
}

View File

@@ -1,318 +1,194 @@
/**
* Copyright (c) 2023 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.benchmark
import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vitorpamplona.quartz.crypto.CryptoUtils
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.GiftWrapEvent
import com.vitorpamplona.quartz.events.NIP24Factory
import com.vitorpamplona.quartz.events.SealedGossipEvent
import com.vitorpamplona.quartz.signers.NostrSignerInternal
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import junit.framework.TestCase
import org.junit.Assert
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* Benchmark, which will execute on an Android device.
*
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will
* output the result. Modify your code to see how it affects performance.
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will output the
* result. Modify your code to see how it affects performance.
*/
@RunWith(AndroidJUnit4::class)
class GiftWrapBenchmark {
@get:Rule val benchmarkRule = BenchmarkRule()
@get:Rule
val benchmarkRule = BenchmarkRule()
fun basePerformanceTest(
message: String,
expectedLength: Int,
) {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
fun basePerformanceTest(message: String, expectedLength: Int) {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
var events: NIP24Factory.Result? = null
val countDownLatch = CountDownLatch(1)
var events: NIP24Factory.Result? = null
val countDownLatch = CountDownLatch(1)
NIP24Factory().createMsgNIP24(
message,
listOf(receiver.pubKey),
sender
) {
events = it
countDownLatch.countDown()
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
val countDownLatch2 = CountDownLatch(1)
Assert.assertEquals(expectedLength, events!!.wraps.map { println("TEST ${it.toJson()}"); it.toJson() }.joinToString("").length)
// Simulate Receiver
events!!.wraps.forEach {
it.checkSignature()
val keyToUse = if (it.recipientPubKey() == sender.pubKey) sender else receiver
it.cachedGift(keyToUse) { event ->
event.checkSignature()
if (event is SealedGossipEvent) {
event.cachedGossip(keyToUse) { innerData ->
Assert.assertEquals(message, innerData.content)
countDownLatch2.countDown()
}
} else {
Assert.fail("Wrong Event")
}
}
}
assertTrue(countDownLatch2.await(1, TimeUnit.SECONDS))
NIP24Factory().createMsgNIP24(
message,
listOf(receiver.pubKey),
sender,
) {
events = it
countDownLatch.countDown()
}
fun receivePerformanceTest(message: String) {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
var giftWrap: GiftWrapEvent? = null
val countDownLatch = CountDownLatch(1)
val countDownLatch2 = CountDownLatch(1)
NIP24Factory().createMsgNIP24(
message,
listOf(receiver.pubKey),
sender
) {
giftWrap = it.wraps.first()
countDownLatch.countDown()
Assert.assertEquals(
expectedLength,
events!!
.wraps
.map {
println("TEST ${it.toJson()}")
it.toJson()
}
.joinToString("")
.length,
)
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
// Simulate Receiver
events!!.wraps.forEach {
it.checkSignature()
val keyToUse = if (giftWrap!!.recipientPubKey() == sender.pubKey) sender else receiver
val giftWrapJson = giftWrap!!.toJson()
val keyToUse = if (it.recipientPubKey() == sender.pubKey) sender else receiver
// Simulate Receiver
benchmarkRule.measureRepeated {
CryptoUtils.clearCache()
val counter = CountDownLatch(1)
it.cachedGift(keyToUse) { event ->
event.checkSignature()
val wrap = Event.fromJson(giftWrapJson) as GiftWrapEvent
wrap.checkSignature()
wrap.cachedGift(keyToUse) {seal ->
seal.checkSignature()
if (seal is SealedGossipEvent) {
seal.cachedGossip(keyToUse) { innerData ->
Assert.assertEquals(message, innerData.content)
counter.countDown()
}
} else {
Assert.fail("Wrong Event")
}
}
TestCase.assertTrue(counter.await(1, TimeUnit.SECONDS))
if (event is SealedGossipEvent) {
event.cachedGossip(keyToUse) { innerData ->
Assert.assertEquals(message, innerData.content)
countDownLatch2.countDown()
}
} else {
Assert.fail("Wrong Event")
}
}
}
assertTrue(countDownLatch2.await(1, TimeUnit.SECONDS))
}
@Test
fun tinyMessageHardCoded() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hola, que tal?", 3402)
}
fun receivePerformanceTest(message: String) {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
var giftWrap: GiftWrapEvent? = null
val countDownLatch = CountDownLatch(1)
NIP24Factory().createMsgNIP24(
message,
listOf(receiver.pubKey),
sender,
) {
giftWrap = it.wraps.first()
countDownLatch.countDown()
}
@Test
fun regularMessageHardCoded() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hi, honey, can you drop by the market and get some bread?", 3746)
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
val keyToUse = if (giftWrap!!.recipientPubKey() == sender.pubKey) sender else receiver
val giftWrapJson = giftWrap!!.toJson()
// Simulate Receiver
benchmarkRule.measureRepeated {
CryptoUtils.clearCache()
val counter = CountDownLatch(1)
val wrap = Event.fromJson(giftWrapJson) as GiftWrapEvent
wrap.checkSignature()
wrap.cachedGift(keyToUse) { seal ->
seal.checkSignature()
if (seal is SealedGossipEvent) {
seal.cachedGossip(keyToUse) { innerData ->
Assert.assertEquals(message, innerData.content)
counter.countDown()
}
} else {
Assert.fail("Wrong Event")
}
}
TestCase.assertTrue(counter.await(1, TimeUnit.SECONDS))
}
}
@Test
fun longMessageHardCoded() {
benchmarkRule.measureRepeated {
basePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
5114
)
}
@Test
fun tinyMessageHardCoded() {
benchmarkRule.measureRepeated { basePerformanceTest("Hola, que tal?", 3402) }
}
@Test
fun regularMessageHardCoded() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hi, honey, can you drop by the market and get some bread?", 3746)
}
}
@Test
fun receivesTinyMessage() {
receivePerformanceTest("Hola, que tal?")
@Test
fun longMessageHardCoded() {
benchmarkRule.measureRepeated {
basePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
5114,
)
}
}
@Test
fun receivesRegularMessage() {
receivePerformanceTest("Hi, honey, can you drop by the market and get some bread?")
}
@Test
fun receivesTinyMessage() {
receivePerformanceTest("Hola, que tal?")
}
@Test
fun receivesLongMessageHardCoded() {
receivePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. "
)
}
@Test
fun receivesRegularMessage() {
receivePerformanceTest("Hi, honey, can you drop by the market and get some bread?")
}
/*
@Test
fun tinyMessageHardCodedCompressed() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hola, que tal?", 2318)
}
}
@Test
fun regularMessageHardCodedCompressed() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hi, honey, can you drop by the market and get some bread?", 2406)
}
}
@Test
fun longMessageHardCodedCompressed() {
benchmarkRule.measureRepeated {
basePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
2722
)
}
}*/
/*
@Test
fun tinyMessageJSONCompressed() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hola, que tal?", 2318)
}
}
@Test
fun regularMessageJSONCompressed() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hi, honey, can you drop by the market and get some bread?", 2394)
}
}
@Test
fun longMessageJSONCompressed() {
benchmarkRule.measureRepeated {
basePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
2714
)
}
}*/
/*
@Test
fun tinyMessageJSON() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hola, que tal?", 3154)
}
}
@Test
fun regularMessageJSON() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hi, honey, can you drop by the market and get some bread?", 3298)
}
}
@Test
fun longMessageJSON() {
benchmarkRule.measureRepeated {
basePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
3938
)
}
}*/
/*
@Test
fun tinyMessageJackson() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hola, que tal?", 3154)
}
}
@Test
fun regularMessageJackson() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hi, honey, can you drop by the market and get some bread?", 3298)
}
}
@Test
fun longMessageJackson() {
benchmarkRule.measureRepeated {
basePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
3938
)
}
} */
/*
@Test
fun tinyMessageKotlin() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hola, que tal?", 3154)
}
}
@Test
fun regularMessageKotlin() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hi, honey, can you drop by the market and get some bread?", 3298)
}
}
@Test
fun longMessageKotlin() {
benchmarkRule.measureRepeated {
basePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
3938
)
}
}*/
/*
@Test
fun tinyMessageCSV() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hola, que tal?", 2960)
}
}
@Test
fun regularMessageCSV() {
benchmarkRule.measureRepeated {
basePerformanceTest("Hi, honey, can you drop by the market and get some bread?", 3112)
}
}
@Test
fun longMessageCSV() {
benchmarkRule.measureRepeated {
basePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
3752
)
}
}*/
}
@Test
fun receivesLongMessageHardCoded() {
receivePerformanceTest(
"My queen, you are nothing short of royalty to me. You possess more beauty in the nail of your pinkie toe than everything else in this world combined. I am astounded by your grace, generosity, and graciousness. I am so lucky to know you. ",
)
}
}

View File

@@ -1,3 +1,23 @@
/**
* Copyright (c) 2023 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.benchmark
import androidx.benchmark.junit4.BenchmarkRule
@@ -13,179 +33,194 @@ import com.vitorpamplona.quartz.events.Gossip
import com.vitorpamplona.quartz.events.SealedGossipEvent
import com.vitorpamplona.quartz.signers.NostrSigner
import com.vitorpamplona.quartz.signers.NostrSignerInternal
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import junit.framework.TestCase.assertNotNull
import junit.framework.TestCase.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* Benchmark, which will execute on an Android device.
*
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will
* output the result. Modify your code to see how it affects performance.
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will output the
* result. Modify your code to see how it affects performance.
*/
@RunWith(AndroidJUnit4::class)
class GiftWrapReceivingBenchmark {
@get:Rule val benchmarkRule = BenchmarkRule()
@get:Rule
val benchmarkRule = BenchmarkRule()
fun createWrap(
sender: NostrSigner,
receiver: NostrSigner,
): GiftWrapEvent {
val countDownLatch = CountDownLatch(1)
var wrap: GiftWrapEvent? = null
fun createWrap(sender: NostrSigner, receiver: NostrSigner): GiftWrapEvent {
val countDownLatch = CountDownLatch(1)
var wrap: GiftWrapEvent? = null
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender,
) {
SealedGossipEvent.create(
event = it,
encryptTo = receiver.pubKey,
signer = sender,
) {
GiftWrapEvent.create(
event = it,
recipientPubKey = receiver.pubKey,
) {
SealedGossipEvent.create(
event = it,
encryptTo = receiver.pubKey,
signer = sender
) {
GiftWrapEvent.create(
event = it,
recipientPubKey = receiver.pubKey
) {
wrap = it
countDownLatch.countDown()
}
}
wrap = it
countDownLatch.countDown()
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
return wrap!!
}
}
fun createSeal(sender: NostrSigner, receiver: NostrSigner): SealedGossipEvent {
val countDownLatch = CountDownLatch(1)
var seal: SealedGossipEvent? = null
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender
) {
SealedGossipEvent.create(
event = it,
encryptTo = receiver.pubKey,
signer = sender
) {
seal = it
countDownLatch.countDown()
}
}
return wrap!!
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
fun createSeal(
sender: NostrSigner,
receiver: NostrSigner,
): SealedGossipEvent {
val countDownLatch = CountDownLatch(1)
var seal: SealedGossipEvent? = null
return seal!!
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender,
) {
SealedGossipEvent.create(
event = it,
encryptTo = receiver.pubKey,
signer = sender,
) {
seal = it
countDownLatch.countDown()
}
}
@Test
fun parseWrapFromString() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
val str = createWrap(sender, receiver).toJson()
return seal!!
}
benchmarkRule.measureRepeated {
Event.fromJson(str)
}
@Test
fun parseWrapFromString() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val str = createWrap(sender, receiver).toJson()
benchmarkRule.measureRepeated { Event.fromJson(str) }
}
@Test
fun checkId() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val wrap = createWrap(sender, receiver)
benchmarkRule.measureRepeated { wrap.hasCorrectIDHash() }
}
@Test
fun checkSignature() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val wrap = createWrap(sender, receiver)
benchmarkRule.measureRepeated { wrap.hasVerifiedSignature() }
}
@Test
fun decryptWrapEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val wrap = createWrap(sender, receiver)
benchmarkRule.measureRepeated {
assertNotNull(
CryptoUtils.decryptNIP44v2(
wrap.content,
receiver.keyPair.privKey!!,
wrap.pubKey.hexToByteArray(),
),
)
}
}
@Test
fun checkId() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
@Test
fun parseWrappedEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val wrap = createWrap(sender, receiver)
val wrap = createWrap(sender, receiver)
benchmarkRule.measureRepeated {
wrap.hasCorrectIDHash()
}
val innerJson =
CryptoUtils.decryptNIP44v2(
wrap.content,
receiver.keyPair.privKey!!,
wrap.pubKey.hexToByteArray(),
)
benchmarkRule.measureRepeated { assertNotNull(innerJson?.let { Event.fromJson(it) }) }
}
@Test
fun decryptSealedEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val seal = createSeal(sender, receiver)
benchmarkRule.measureRepeated {
assertNotNull(
CryptoUtils.decryptNIP44v2(
seal.content,
receiver.keyPair.privKey!!,
seal.pubKey.hexToByteArray(),
),
)
}
}
@Test
fun checkSignature() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
@Test
fun parseSealedEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val wrap = createWrap(sender, receiver)
val seal = createSeal(sender, receiver)
benchmarkRule.measureRepeated {
wrap.hasVerifiedSignature()
}
}
val innerJson =
CryptoUtils.decryptNIP44v2(
seal.content,
receiver.keyPair.privKey!!,
seal.pubKey.hexToByteArray(),
)
@Test
fun decryptWrapEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val wrap = createWrap(sender, receiver)
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.decryptNIP44v2(wrap.content, receiver.keyPair.privKey!!, wrap.pubKey.hexToByteArray()))
}
}
@Test
fun parseWrappedEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val wrap = createWrap(sender, receiver)
val innerJson = CryptoUtils.decryptNIP44v2(wrap.content, receiver.keyPair.privKey!!, wrap.pubKey.hexToByteArray())
benchmarkRule.measureRepeated {
assertNotNull(innerJson?.let { Event.fromJson(it) })
}
}
@Test
fun decryptSealedEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val seal = createSeal(sender, receiver)
benchmarkRule.measureRepeated {
assertNotNull(CryptoUtils.decryptNIP44v2(seal.content, receiver.keyPair.privKey!!, seal.pubKey.hexToByteArray()))
}
}
@Test
fun parseSealedEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val seal = createSeal(sender, receiver)
val innerJson = CryptoUtils.decryptNIP44v2(seal.content, receiver.keyPair.privKey!!, seal.pubKey.hexToByteArray())
benchmarkRule.measureRepeated {
assertNotNull(innerJson?.let { Gossip.fromJson(it) })
}
}
}
benchmarkRule.measureRepeated { assertNotNull(innerJson?.let { Gossip.fromJson(it) }) }
}
}

View File

@@ -1,190 +1,201 @@
/**
* Copyright (c) 2023 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.benchmark
import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vitorpamplona.quartz.crypto.CryptoUtils
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.events.ChatMessageEvent
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.GiftWrapEvent
import com.vitorpamplona.quartz.events.Gossip
import com.vitorpamplona.quartz.events.SealedGossipEvent
import com.vitorpamplona.quartz.signers.NostrSignerInternal
import junit.framework.TestCase.assertNotNull
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import junit.framework.TestCase.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* Benchmark, which will execute on an Android device.
*
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will
* output the result. Modify your code to see how it affects performance.
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will output the
* result. Modify your code to see how it affects performance.
*/
@RunWith(AndroidJUnit4::class)
class GiftWrapSigningBenchmark {
@get:Rule val benchmarkRule = BenchmarkRule()
@get:Rule
val benchmarkRule = BenchmarkRule()
@Test
fun createMessageEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
@Test
fun createMessageEvent() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
benchmarkRule.measureRepeated {
val countDownLatch = CountDownLatch(1)
benchmarkRule.measureRepeated {
val countDownLatch = CountDownLatch(1)
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender,
) {
countDownLatch.countDown()
}
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender
) {
countDownLatch.countDown()
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
}
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
}
@Test
fun sealMessage() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val countDownLatch = CountDownLatch(1)
var msg: ChatMessageEvent? = null
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender,
) {
msg = it
countDownLatch.countDown()
}
@Test
fun sealMessage() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
val countDownLatch = CountDownLatch(1)
benchmarkRule.measureRepeated {
val countDownLatch2 = CountDownLatch(1)
SealedGossipEvent.create(
event = msg!!,
encryptTo = receiver.pubKey,
signer = sender,
) {
countDownLatch2.countDown()
}
var msg: ChatMessageEvent? = null
assertTrue(countDownLatch2.await(1, TimeUnit.SECONDS))
}
}
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender
@Test
fun wrapSeal() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val countDownLatch = CountDownLatch(1)
var seal: SealedGossipEvent? = null
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender,
) {
SealedGossipEvent.create(
event = it,
encryptTo = receiver.pubKey,
signer = sender,
) {
seal = it
countDownLatch.countDown()
}
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
benchmarkRule.measureRepeated {
val countDownLatch2 = CountDownLatch(1)
GiftWrapEvent.create(
event = seal!!,
recipientPubKey = receiver.pubKey,
) {
countDownLatch2.countDown()
}
assertTrue(countDownLatch2.await(1, TimeUnit.SECONDS))
}
}
@Test
fun wrapToString() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val countDownLatch = CountDownLatch(1)
var wrap: GiftWrapEvent? = null
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender,
) {
SealedGossipEvent.create(
event = it,
encryptTo = receiver.pubKey,
signer = sender,
) {
GiftWrapEvent.create(
event = it,
recipientPubKey = receiver.pubKey,
) {
msg = it
countDownLatch.countDown()
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
benchmarkRule.measureRepeated {
val countDownLatch2 = CountDownLatch(1)
SealedGossipEvent.create(
event = msg!!,
encryptTo = receiver.pubKey,
signer = sender
) {
countDownLatch2.countDown()
}
assertTrue(countDownLatch2.await(1, TimeUnit.SECONDS))
wrap = it
countDownLatch.countDown()
}
}
}
@Test
fun wrapSeal() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
val countDownLatch = CountDownLatch(1)
var seal: SealedGossipEvent? = null
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender
) {
SealedGossipEvent.create(
event = it,
encryptTo = receiver.pubKey,
signer = sender
) {
seal = it
countDownLatch.countDown()
}
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
benchmarkRule.measureRepeated {
val countDownLatch2 = CountDownLatch(1)
GiftWrapEvent.create(
event = seal!!,
recipientPubKey = receiver.pubKey
) {
countDownLatch2.countDown()
}
assertTrue(countDownLatch2.await(1, TimeUnit.SECONDS))
}
}
@Test
fun wrapToString() {
val sender = NostrSignerInternal(KeyPair())
val receiver = NostrSignerInternal(KeyPair())
val countDownLatch = CountDownLatch(1)
var wrap: GiftWrapEvent? = null
ChatMessageEvent.create(
msg = "Hi there! This is a test message",
to = listOf(receiver.pubKey),
subject = "Party Tonight",
replyTos = emptyList(),
mentions = emptyList(),
zapReceiver = null,
markAsSensitive = true,
zapRaiserAmount = 10000,
geohash = null,
signer = sender
) {
SealedGossipEvent.create(
event = it,
encryptTo = receiver.pubKey,
signer = sender
) {
GiftWrapEvent.create(
event = it,
recipientPubKey = receiver.pubKey
) {
wrap = it
countDownLatch.countDown()
}
}
}
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
benchmarkRule.measureRepeated {
wrap!!.toJson()
}
}
}
benchmarkRule.measureRepeated { wrap!!.toJson() }
}
}

View File

@@ -1,3 +1,23 @@
/**
* Copyright (c) 2023 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.benchmark
import androidx.benchmark.junit4.BenchmarkRule
@@ -11,46 +31,38 @@ import org.junit.runner.RunWith
/**
* Benchmark, which will execute on an Android device.
*
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will
* output the result. Modify your code to see how it affects performance.
* The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will output the
* result. Modify your code to see how it affects performance.
*/
@RunWith(AndroidJUnit4::class)
class HexBenchmark {
@get:Rule val benchmarkRule = BenchmarkRule()
@get:Rule
val benchmarkRule = BenchmarkRule()
val testHex = "48a72b485d38338627ec9d427583551f9af4f016c739b8ec0d6313540a8b12cf"
val TestHex = "48a72b485d38338627ec9d427583551f9af4f016c739b8ec0d6313540a8b12cf"
@Test
fun hexDecodeOurs() {
benchmarkRule.measureRepeated { com.vitorpamplona.quartz.encoders.Hex.decode(testHex) }
}
@Test
fun hexDecodeOurs() {
benchmarkRule.measureRepeated {
com.vitorpamplona.quartz.encoders.Hex.decode(TestHex)
}
@Test
fun hexEncodeOurs() {
val bytes = com.vitorpamplona.quartz.encoders.Hex.decode(testHex)
benchmarkRule.measureRepeated {
assertEquals(testHex, com.vitorpamplona.quartz.encoders.Hex.encode(bytes))
}
}
@Test
fun hexEncodeOurs() {
val bytes = com.vitorpamplona.quartz.encoders.Hex.decode(TestHex)
@Test
fun hexDecodeBaseSecp() {
benchmarkRule.measureRepeated { fr.acinq.secp256k1.Hex.decode(testHex) }
}
benchmarkRule.measureRepeated {
assertEquals(TestHex, com.vitorpamplona.quartz.encoders.Hex.encode(bytes))
}
}
@Test
fun hexEncodeBaseSecp() {
val bytes = fr.acinq.secp256k1.Hex.decode(testHex)
@Test
fun hexDecodeBaseSecp() {
benchmarkRule.measureRepeated {
fr.acinq.secp256k1.Hex.decode(TestHex)
}
}
@Test
fun hexEncodeBaseSecp() {
val bytes = fr.acinq.secp256k1.Hex.decode(TestHex)
benchmarkRule.measureRepeated {
assertEquals(TestHex, fr.acinq.secp256k1.Hex.encode(bytes))
}
}
}
benchmarkRule.measureRepeated { assertEquals(testHex, fr.acinq.secp256k1.Hex.encode(bytes)) }
}
}

File diff suppressed because one or more lines are too long