Skip to content

Commit

Permalink
NO-TICKET - Add metadata change logs (#1852)
Browse files Browse the repository at this point in the history
  • Loading branch information
gslevinkov authored Jun 20, 2023
1 parent 5cf0e9d commit baebace
Show file tree
Hide file tree
Showing 14 changed files with 200 additions and 38 deletions.
2 changes: 2 additions & 0 deletions app/src/main/java/org/p2p/wallet/auth/AuthModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import org.p2p.wallet.auth.interactor.AuthLogoutInteractor
import org.p2p.wallet.auth.interactor.CreateWalletInteractor
import org.p2p.wallet.auth.interactor.FileInteractor
import org.p2p.wallet.auth.interactor.GatewayMetadataMerger
import org.p2p.wallet.auth.interactor.MetadataChangesLogger
import org.p2p.wallet.auth.interactor.MetadataInteractor
import org.p2p.wallet.auth.interactor.OnboardingInteractor
import org.p2p.wallet.auth.interactor.UserSignUpInteractor
Expand Down Expand Up @@ -191,6 +192,7 @@ object AuthModule {
factoryOf(::UserRestoreInteractor)
factoryOf(::GatewayMetadataMerger)
factoryOf(::MetadataInteractor)
factoryOf(::MetadataChangesLogger)
singleOf(::RestoreStateMachine)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,15 @@ class CountryCodeXmlParser(
private fun getMaskForCountryCode(countryCode: String, phoneCode: String): String {
return try {
val exampleNumber: Phonenumber.PhoneNumber? = phoneNumberUtil.getExampleNumber(countryCode)
val internationalFormat = phoneNumberUtil.format(
exampleNumber,
PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL
)
internationalFormat.replace("+$phoneCode", emptyString())
if (exampleNumber != null) {
val internationalFormat = phoneNumberUtil.format(
exampleNumber,
PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL
)
internationalFormat.replace("+$phoneCode", emptyString())
} else {
emptyString()
}
} catch (e: Throwable) {
Timber.i(e, "Get mask for country code failed")
emptyString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ interface BorshSerializable {
fun BorshBuffer.write(vararg objects: Any): BorshBuffer {
val validatedObjects: List<Any> = objects.map { if (it is JsonObject) it.toString() else it }
validatedObjects.forEach {
if (it is ByteArray) {
this.writeFixedArray(it)
} else {
this.write(it)
}
Timber.tag("BorshBuffer").d("Written to borsh: $it")
this.write(it)
}
return this
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ package org.p2p.wallet.auth.gateway.repository.mapper
import com.google.gson.Gson
import com.google.gson.JsonObject
import org.near.borshj.Borsh
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.time.DurationUnit
import kotlin.time.toDuration
import org.p2p.core.utils.Constants
import org.p2p.solanaj.utils.crypto.toBase64Instance
import org.p2p.wallet.auth.gateway.api.request.ConfirmRegisterWalletRequest
import org.p2p.wallet.auth.gateway.api.request.GatewayOnboardingMetadataCiphered
Expand All @@ -15,16 +21,10 @@ import org.p2p.wallet.auth.gateway.repository.model.GatewayOnboardingMetadata
import org.p2p.wallet.auth.gateway.repository.model.PushServiceError
import org.p2p.wallet.auth.model.PhoneNumber
import org.p2p.wallet.auth.web3authsdk.response.Web3AuthSignUpResponse
import org.p2p.wallet.settings.DeviceInfoHelper
import org.p2p.wallet.utils.Base58String
import org.p2p.core.utils.Constants
import org.p2p.wallet.utils.toByteArray
import org.p2p.wallet.utils.toJsonObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.time.DurationUnit
import kotlin.time.toDuration
import org.p2p.wallet.settings.DeviceInfoHelper

const val TIMESTAMP_PATTERN_GATEWAY_SERVICE = "yyyy-MM-dd HH:mm:ssXXX"

Expand Down Expand Up @@ -132,6 +132,7 @@ class GatewayServiceCreateWalletMapper(
phoneNumberTimestampSec = epochUnixTimeSeconds,
socialShareOwnerEmail = socialShareOwnerId,
emailTimestampSec = epochUnixTimeSeconds,
authProviderTimestampSec = epochUnixTimeSeconds
)
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import com.google.gson.Gson
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.time.DurationUnit
import kotlin.time.toDuration
import kotlin.time.Duration.Companion.milliseconds
import org.p2p.core.rpc.JsonRpc
import org.p2p.solanaj.utils.crypto.toBase64Instance
import org.p2p.wallet.auth.gateway.api.request.GatewayOnboardingMetadataCiphered
Expand Down Expand Up @@ -42,7 +41,7 @@ class GatewayServiceUpdateMetadataMapper(
userSeedPhrase: List<String>,
metadata: GatewayOnboardingMetadata,
): JsonRpc<Map<String, Any>, UpdateMetadataResponse> {
val epochUnixTime = System.currentTimeMillis().toDuration(DurationUnit.MILLISECONDS)
val epochUnixTime = System.currentTimeMillis().milliseconds
val encryptedMetadata: GatewayOnboardingMetadataCiphered = onboardingMetadataCipher.encryptMetadata(
mnemonicPhrase = userSeedPhrase,
onboardingMetadata = metadata
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.p2p.wallet.auth.interactor

import androidx.core.content.edit
import android.content.SharedPreferences
import com.google.gson.Gson
import org.p2p.wallet.BuildConfig
import org.p2p.wallet.auth.gateway.repository.model.GatewayOnboardingMetadata
import org.p2p.wallet.utils.DateTimeUtils

private const val KEY_CHANGES_LOG = "KEY_CHANGES_LOG"

class MetadataChangesLogger(
private val sharedPreferences: SharedPreferences,
private val gson: Gson
) {
val logs: Set<String>
get() = sharedPreferences.getStringSet(KEY_CHANGES_LOG, emptySet()).orEmpty()

fun logChange(
metadataOld: GatewayOnboardingMetadata?,
metadataNew: GatewayOnboardingMetadata
) {
if (BuildConfig.DEBUG) {
val metadataLogs =
sharedPreferences.getStringSet(KEY_CHANGES_LOG, emptySet()) ?: mutableSetOf()

val logEntry = buildString {
append(DateTimeUtils.getFormattedDateAndTime(System.currentTimeMillis()))
append(":")
appendLine()
append("before=${gson.toJson(metadataOld)}")
appendLine()
append("after=${gson.toJson(metadataNew)}")
appendLine()
}
val newMetadataLogs = HashSet(metadataLogs).plus(logEntry)
sharedPreferences.edit { putStringSet(KEY_CHANGES_LOG, newMetadataLogs) }
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class MetadataInteractor(
private val gatewayMetadataMerger: GatewayMetadataMerger,
private val ethereumInteractor: EthereumInteractor,
private val bridgeFeatureToggle: EthAddressEnabledFeatureToggle,
private val metadataChangesLogger: MetadataChangesLogger
) {

var currentMetadata: GatewayOnboardingMetadata? = null
Expand Down Expand Up @@ -108,6 +109,10 @@ class MetadataInteractor(
}

suspend fun updateMetadata(metadata: GatewayOnboardingMetadata) {
metadataChangesLogger.logChange(
metadataOld = currentMetadata,
metadataNew = metadata
)
currentMetadata = metadata
tryToUploadMetadata(metadata)
}
Expand Down Expand Up @@ -198,6 +203,10 @@ class MetadataInteractor(
}
updatedMetadata
} ?: serverMetadata
metadataChangesLogger.logChange(
metadataOld = currentMetadata,
metadataNew = finalMetadata
)
currentMetadata = finalMetadata
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package org.p2p.wallet.auth.web3authsdk

import org.p2p.wallet.auth.analytics.OnboardingAnalytics
import org.p2p.wallet.infrastructure.network.environment.TorusEnvironment
import org.p2p.wallet.utils.DateTimeUtils.PATTERN_HH_MM_SS_SS
import org.p2p.wallet.utils.DateTimeUtils.getFormattedDate
import org.p2p.wallet.utils.emptyString
import timber.log.Timber
import java.util.Date
import kotlin.time.Duration
import kotlin.time.DurationUnit
import kotlin.time.toDuration
import org.p2p.wallet.auth.analytics.OnboardingAnalytics
import org.p2p.wallet.infrastructure.network.environment.TorusEnvironment
import org.p2p.wallet.utils.DateTimeUtils.PATTERN_HH_MM_SS_SS
import org.p2p.wallet.utils.DateTimeUtils.getFormattedDate
import org.p2p.wallet.utils.emptyString

private const val EXPECTED_REQUEST_TIME_SEC = 15
private const val TAG = "Web3AuthDuration"
Expand All @@ -35,10 +35,10 @@ class Web3AuthDurationTracker(
Timber.tag(TAG).i(
buildString {
append("--> Web3Auth request: ")
append("$methodName;")
append("${torusNetwork.verifier};")
append("${torusNetwork.subVerifier};")
append("${torusNetwork.baseUrl};")
append("$methodName; ")
append("${torusNetwork.verifier}; ")
append("${torusNetwork.subVerifier}; ")
append("${torusNetwork.baseUrl}; ")
append("date=${getFormattedDate(Date().time, PATTERN_HH_MM_SS_SS)}")
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,25 @@ import androidx.lifecycle.lifecycleScope
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.gson.Gson
import org.json.JSONObject
import org.koin.android.ext.android.inject
import java.nio.charset.Charset
import org.p2p.solanaj.utils.crypto.toBase64Instance
import org.p2p.uikit.utils.toast
import org.p2p.wallet.R
import org.p2p.wallet.auth.gateway.api.request.GatewayOnboardingMetadataCiphered
import org.p2p.wallet.auth.gateway.repository.mapper.GatewayServiceOnboardingMetadataCipher
import org.p2p.wallet.auth.interactor.MetadataChangesLogger
import org.p2p.wallet.auth.interactor.MetadataInteractor
import org.p2p.wallet.auth.model.MetadataLoadStatus
import org.p2p.wallet.auth.repository.UserSignUpDetailsStorage
import org.p2p.wallet.common.mvp.BaseFragment
import org.p2p.wallet.databinding.FragmentDebugWeb3Binding
import org.p2p.wallet.utils.fromJsonReified
import org.p2p.wallet.utils.popBackStack
import org.p2p.wallet.utils.shareText
import org.p2p.wallet.utils.viewbinding.viewBinding

@SuppressLint("SetTextI18n")
Expand All @@ -27,6 +36,8 @@ class DebugWeb3Fragment : BaseFragment(R.layout.fragment_debug_web3) {
private val binding: FragmentDebugWeb3Binding by viewBinding()
private val metadataInteractor: MetadataInteractor by inject()
private val signUpDetailsStorage: UserSignUpDetailsStorage by inject()
private val metadataDecipher: GatewayServiceOnboardingMetadataCipher by inject()
private val metadataChangesLogger: MetadataChangesLogger by inject()
private val gson: Gson by inject()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Expand All @@ -38,6 +49,10 @@ class DebugWeb3Fragment : BaseFragment(R.layout.fragment_debug_web3) {
buttonLoadMetadata.setOnClickListener {
lifecycleScope.launchWhenResumed { loadMetadata() }
}

buttonDecipherMetadata.setOnClickListener {
decipherMetadata()
}
}
}

Expand All @@ -46,15 +61,19 @@ class DebugWeb3Fragment : BaseFragment(R.layout.fragment_debug_web3) {

val web3AuthData = signUpDetailsStorage.getLastSignUpUserDetails()
val web3DataJson = web3AuthData
?.let { JSONObject(gson.toJson(it)).toString(2) }
?.toUiJson()
?: "None"

val metadataJson = metadataInteractor.currentMetadata
?.let { JSONObject(gson.toJson(it)).toString(2) }
?.toUiJson()
?: if (web3AuthData != null) "Not loaded" else "None"

textViewWeb3Value.text = web3DataJson
textViewMetadataValue.text = metadataJson

buttonMetadataLogs.setOnClickListener {
requireContext().shareText(metadataChangesLogger.logs.joinToString("\n"))
}
}

private suspend fun loadMetadata() {
Expand Down Expand Up @@ -83,4 +102,45 @@ class DebugWeb3Fragment : BaseFragment(R.layout.fragment_debug_web3) {
}
binding.buttonLoadMetadata.setLoading(false)
}

private fun decipherMetadata() {
val cipheredMetadata = binding.editTextDecipherMetadata.text?.toString()
?.trim()
.orEmpty()
if (cipheredMetadata.isNotBlank()) {
// get json like GatewayOnboardingMetadataCiphered
val metadataAsJson =
kotlin.runCatching {
gson.fromJsonReified<GatewayOnboardingMetadataCiphered>(
cipheredMetadata.toBase64Instance()
.decodeToBytes()
.toString(Charset.defaultCharset())
)
}
.onFailure { toast(it.toString()) }
.getOrNull()
val seedPhrase = signUpDetailsStorage.getLastSignUpUserDetails()
?.signUpDetails
?.mnemonicPhraseWords

if (seedPhrase != null && metadataAsJson != null) {
kotlin.runCatching { metadataDecipher.decryptMetadata(seedPhrase, metadataAsJson) }
.onSuccess {
MaterialAlertDialogBuilder(requireContext())
.setMessage(it.toUiJson())
.setPositiveButton(R.string.common_ok) { d, _ ->
d.dismiss()
}
.setNegativeButton(R.string.common_share) { _, _ ->
requireContext().shareText(it.toUiJson())
}
.show()
}
}
}
}

private fun Any.toUiJson(): String {
return JSONObject(gson.toJson(this)).toString(2)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import retrofit2.converter.scalars.ScalarsConverterFactory
import java.math.BigDecimal
import java.util.concurrent.TimeUnit
import org.p2p.core.rpc.RPC_RETROFIT_QUALIFIER
import org.p2p.core.rpc.RpcApi
import org.p2p.solanaj.utils.crypto.Base64String
import org.p2p.wallet.BuildConfig
import org.p2p.wallet.R
Expand Down Expand Up @@ -92,6 +93,15 @@ object NetworkModule : InjectionModule {
interceptor = RpcInterceptor(get(), get())
)
}
single<RpcApi> {
getRetrofit(
// no need for baseUrl here, we pass URL inside RpcApi
baseUrl = "http://localhost/",
tag = "RpcApi",
interceptor = null
)
.create(RpcApi::class.java)
}
single(named(REN_POOL_RETROFIT_QUALIFIER)) {
val environment = get<NetworkEnvironmentManager>().loadRpcEnvironment()
val rpcApiUrl = environment.endpoint
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ class SellInteractor(
sellRepository.isSellAllowedForUser()

val debugInfo = buildString {
append("isFeatureEnabled=${sellEnabledFeatureToggle.isFeatureEnabled}")
append("isUserBalancePositive=${isUserBalancePositive()}")
append("isSellAllowedForUser=${sellRepository.isSellAllowedForUser()}")
append("isFeatureEnabled=${sellEnabledFeatureToggle.isFeatureEnabled} ")
append("isUserBalancePositive=${isUserBalancePositive()} ")
append("isSellAllowedForUser=${sellRepository.isSellAllowedForUser()} ")
}
Timber.i("Checking if sell is available: $debugInfo")
return isSellAvailable
Expand Down
Loading

0 comments on commit baebace

Please sign in to comment.