Updated on 2026-08-14

This commit is contained in:
Tangem 2018-12-18 14:11:24 +03:00
commit 2922eab134
24 changed files with 2106 additions and 937 deletions

View file

@ -9,31 +9,20 @@ import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.Html
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import org.json.JSONException
import com.tangem.data.network.ElectrumRequest
import com.tangem.data.network.ServerApiCommon
import com.tangem.data.network.ServerApiElectrum
import com.tangem.data.network.ServerApiInfura
import com.tangem.data.network.model.InfuraResponse
import com.tangem.tangemcard.android.reader.NfcManager
import com.tangem.domain.wallet.*
import com.tangem.domain.wallet.btc.BtcData
import com.tangem.data.Blockchain
import com.tangem.domain.wallet.CoinEngine
import com.tangem.domain.wallet.CoinEngineFactory
import com.tangem.domain.wallet.TangemContext
import com.tangem.tangemcard.android.reader.NfcManager
import com.tangem.tangemcard.data.TangemCard
import com.tangem.tangemcard.data.loadFromBundle
import com.tangem.tangemcard.util.Util
import com.tangem.util.*
import com.tangem.util.UtilHelper
import com.tangem.wallet.R
import com.tangem.wallet.R.string.fee
import kotlinx.android.synthetic.main.activity_confirm_payment.*
import java.io.IOException
import java.math.BigDecimal
import java.math.BigInteger
import java.math.RoundingMode
import java.util.*
class ConfirmPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
@ -44,23 +33,20 @@ class ConfirmPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
private var nfcManager: NfcManager? = null
private var serverApiCommon: ServerApiCommon = ServerApiCommon()
private var serverApiInfura: ServerApiInfura = ServerApiInfura()
private var serverApiElectrum: ServerApiElectrum = ServerApiElectrum()
// private var serverApiCommon: ServerApiCommon = ServerApiCommon()
// private var serverApiInfura: ServerApiInfura = ServerApiInfura()
// private var serverApiElectrum: ServerApiElectrum = ServerApiElectrum()
private lateinit var ctx: TangemContext
private lateinit var amount: CoinEngine.Amount
private var feeRequestSuccess = false
// private var balanceRequestSuccess = false
private var minFee: CoinEngine.Amount? = null
private var maxFee: CoinEngine.Amount? = null
private var normalFee: CoinEngine.Amount? = null
// private var feeRequestSuccess = false
// private var balanceRequestSuccess = false
private var isIncludeFee: Boolean = true
private var requestPIN2Count = 0
private var nodeCheck = true
private var dtVerified: Date? = null
private var calcSize: Int = 0
// private var calcSize: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@ -86,7 +72,7 @@ class ConfirmPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
amount = CoinEngine.Amount(intent.getStringExtra(SignPaymentActivity.EXTRA_AMOUNT), intent.getStringExtra(SignPaymentActivity.EXTRA_AMOUNT_CURRENCY))
if (ctx.blockchain == Blockchain.Token && amount.currency!="ETH")
if (ctx.blockchain == Blockchain.Token && amount.currency != "ETH")
tvIncFee.visibility = View.INVISIBLE
else
tvIncFee.visibility = View.VISIBLE
@ -99,31 +85,24 @@ class ConfirmPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
etFee.setText("")
btnSend.visibility = View.INVISIBLE
feeRequestSuccess = false
// feeRequestSuccess = false
// balanceRequestSuccess = false
if (ctx.blockchain == Blockchain.Ethereum || ctx.blockchain == Blockchain.EthereumTestNet || ctx.blockchain == Blockchain.Token) {
rgFee.isEnabled = false
requestInfura(ServerApiInfura.INFURA_ETH_GAS_PRICE)
} else if (ctx.blockchain == Blockchain.BitcoinCash) {
rgFee.isEnabled = false
progressBar.visibility = View.VISIBLE
requestElectrum(ctx, ElectrumRequest.getFee())
// requestInfura(ServerApiInfura.INFURA_ETH_GAS_PRICE)
} else {
rgFee.isEnabled = true
// requestElectrum(ctx.card, ElectrumRequest.checkBalance(ctx.card!!.wallet))
ctx.coinData!!.resetFailedBalanceRequestCounter()
// ctx.coinData!!.resetFailedBalanceRequestCounter()
progressBar.visibility = View.VISIBLE
// progressBar.visibility = View.VISIBLE
requestEstimateFee()
// requestEstimateFee()
}
// set listeners
@ -201,146 +180,166 @@ class ConfirmPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
startActivityForResult(intent, REQUEST_CODE_REQUEST_PIN2)
}
// request electrum listener
val electrumBodyListener: ServerApiElectrum.ElectrumRequestDataListener = object : ServerApiElectrum.ElectrumRequestDataListener {
override fun onSuccess(electrumRequest: ElectrumRequest?) {
var fee: BigDecimal
if (electrumRequest!!.isMethod(ElectrumRequest.METHOD_GetFee)) {
try {
//if (etFee.text.toString().isEmpty()) etFee.setText(getString(R.string.empty))
fee = BigDecimal(electrumRequest.resultString) //fee per KB
val coinEngine = CoinEngineFactory.create(ctx)
if (fee == BigDecimal.ZERO) {
requestElectrum(ctx, ElectrumRequest.getFee())
}
progressBar.visibility = View.VISIBLE
if (calcSize.toLong() != 0L) {
fee = fee.multiply(BigDecimal(calcSize.toLong())).divide(BigDecimal(1024)) // (per KB -> per byte)*size
coinEngine!!.requestFee(
object : CoinEngine.BlockchainRequestsCallbacks {
override fun onComplete(success: Boolean) {
if (success) {
onProgress()
// etFee.error = null
// feeRequestSuccess = true
// balanceRequestSuccess = true
progressBar.visibility = View.INVISIBLE
dtVerified = Date()
} else {
requestElectrum(ctx, ElectrumRequest.getFee())
finishWithError(Activity.RESULT_CANCELED, ctx.error)
}
progressBar.visibility = View.INVISIBLE
val relayFee : BigDecimal = BigDecimal(0.00001)
//compare fee to usual relay fee
if (fee.compareTo(relayFee) == -1) {
fee = relayFee
}
fee = fee.setScale(8, RoundingMode.DOWN)
var feeAmount: CoinEngine.Amount = CoinEngine.Amount(fee, "BCH")
minFee = feeAmount
normalFee = feeAmount
maxFee = feeAmount
doSetFee(rgFee.checkedRadioButtonId)
etFee.error = null
btnSend.visibility = View.VISIBLE
feeRequestSuccess = true
dtVerified = Date()
} catch (e: JSONException) {
e.printStackTrace()
}
}
}
override fun onFail(message: String?) {
finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_check_balance_no_connection_with_blockchain_nodes))
}
override fun onProgress() {
doSetFee(rgFee.checkedRadioButtonId)
}
}
serverApiElectrum.setElectrumRequestData(electrumBodyListener)
override fun allowAdvance(): Boolean {
return UtilHelper.isOnline(this@ConfirmPaymentActivity)
}
},
etWallet.text.toString(),
amount)
// request electrum listener
// val electrumBodyListener: ServerApiHelperElectrum.ElectrumRequestDataListener = object : ServerApiHelperElectrum.ElectrumRequestDataListener {
// override fun onSuccess(electrumRequest: ElectrumRequest?) {
// if (electrumRequest!!.isMethod(ElectrumRequest.METHOD_GetBalance)) {
// try {
// if (etFee.text.toString().isEmpty()) etFee.setText(getString(R.string.empty))
// val engine = CoinEngineFactory.create(ctx)
// val balance = engine.convertToAmount(CoinEngine.InternalAmount(electrumRequest.result.getLong("confirmed") + electrumRequest.result.getLong("unconfirmed"), "Satoshi"))
// val amount = CoinEngine.Amount(etAmount.text.toString(), ctx.blockchain.currency)
// if (balance < amount) {
// etFee.error = getString(R.string.not_enough_funds)
// } else {
// etFee.error = null
// balanceRequestSuccess = true
// if (feeRequestSuccess && balanceRequestSuccess) {
// btnSend.visibility = View.VISIBLE
// }
// dtVerified = Date()
// nodeCheck = true
// }
// } catch (e: JSONException) {
// e.printStackTrace()
//// requestElectrum(ctx.card!!, ElectrumRequest.checkBalance(ctx.card!!.wallet))
// }
// }
// }
//
// override fun onFail(message: String?) {
// finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_check_balance_no_connection_with_blockchain_nodes))
// }
//
// }
// serverApiHelperElectrum.setElectrumRequestData(electrumBodyListener)
// request infura eth gasPrice listener
val infuraBodyListener: ServerApiInfura.InfuraBodyListener = object : ServerApiInfura.InfuraBodyListener {
override fun onSuccess(method: String, infuraResponse: InfuraResponse) {
when (method) {
ServerApiInfura.INFURA_ETH_GAS_PRICE -> {
var gasPrice = infuraResponse.result
gasPrice = gasPrice.substring(2)
//TODO - remove Gwei
// rounding gas price to integer gwei
val l = BigInteger(gasPrice, 16).divide(BigInteger.valueOf(1000000000L)).multiply(BigInteger.valueOf(1000000000L))
// val infuraBodyListener: ServerApiInfura.InfuraBodyListener = object : ServerApiInfura.InfuraBodyListener {
// override fun onSuccess(method: String, infuraResponse: InfuraResponse) {
// when (method) {
// ServerApiInfura.INFURA_ETH_GAS_PRICE -> {
// var gasPrice = infuraResponse.result
// gasPrice = gasPrice.substring(2)
// //TODO - remove Gwei
// // rounding gas price to integer gwei
// val l = BigInteger(gasPrice, 16).divide(BigInteger.valueOf(1000000000L)).multiply(BigInteger.valueOf(1000000000L))
//
// //val m = if (ctx.blockchain==Blockchain.Token) BigInteger.valueOf(60000) else BigInteger.valueOf(21000)
// val m = if (amount.currency != "ETH") BigInteger.valueOf(60000) else BigInteger.valueOf(21000)
// val weiMinFee = CoinEngine.InternalAmount(l.multiply(m), "wei")
// val weiNormalFee = CoinEngine.InternalAmount(weiMinFee.multiply(BigDecimal.valueOf(12)).divide(BigDecimal.valueOf(10)), "wei")
// val weiMaxFee = CoinEngine.InternalAmount(weiMinFee.multiply(BigDecimal.valueOf(15)).divide(BigDecimal.valueOf(10)), "wei")
//
// minFee = engine.convertToAmount(weiMinFee)
// normalFee = engine.convertToAmount(weiNormalFee)
// maxFee = engine.convertToAmount(weiMaxFee)
// doSetFee(rgFee.checkedRadioButtonId)
// //etFee.setText(weiNormalFee.toValueString())
// etFee.error = null
// btnSend.visibility = View.VISIBLE
// feeRequestSuccess = true
//// balanceRequestSuccess = true
// dtVerified = Date()
// }
// }
// }
//
// override fun onFail(method: String, message: String) {
// when (method) {
// ServerApiInfura.INFURA_ETH_GAS_PRICE -> {
// finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
// }
// }
// }
// }
// serverApiInfura.setInfuraResponse(infuraBodyListener)
//val m = if (ctx.blockchain==Blockchain.Token) BigInteger.valueOf(60000) else BigInteger.valueOf(21000)
val m = if (amount.currency != "ETH") BigInteger.valueOf(60000) else BigInteger.valueOf(21000)
val weiMinFee = CoinEngine.InternalAmount(l.multiply(m), "wei")
val weiNormalFee = CoinEngine.InternalAmount(weiMinFee.multiply(BigDecimal.valueOf(12)).divide(BigDecimal.valueOf(10)), "wei")
val weiMaxFee = CoinEngine.InternalAmount(weiMinFee.multiply(BigDecimal.valueOf(15)).divide(BigDecimal.valueOf(10)), "wei")
minFee = engine.convertToAmount(weiMinFee)
normalFee = engine.convertToAmount(weiNormalFee)
maxFee = engine.convertToAmount(weiMaxFee)
doSetFee(rgFee.checkedRadioButtonId)
//etFee.setText(weiNormalFee.toValueString())
etFee.error = null
btnSend.visibility = View.VISIBLE
feeRequestSuccess = true
dtVerified = Date()
}
}
}
override fun onFail(method: String, message: String) {
when (method) {
ServerApiInfura.INFURA_ETH_GAS_PRICE -> {
finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
}
}
}
}
serverApiInfura.setInfuraResponse(infuraBodyListener)
// request estimate fee listener
val estimateFeeListener: ServerApiCommon.EstimateFeeListener = object : ServerApiCommon.EstimateFeeListener {
override fun onSuccess(blockCount: Int, estimateFeeResponse: String?) {
var fee: BigDecimal
fee = BigDecimal(estimateFeeResponse) // BTC per 1 kb
if (fee == BigDecimal.ZERO) {
progressBar.visibility = View.INVISIBLE
requestEstimateFee()
}
if (calcSize.toLong() != 0L) {
fee = fee.multiply(BigDecimal(calcSize.toLong())).divide(BigDecimal(1024)) // per Kb -> per byte
} else {
requestEstimateFee()
}
progressBar.visibility = View.INVISIBLE
fee = fee.setScale(8, RoundingMode.DOWN)
when (blockCount) {
ServerApiCommon.ESTIMATE_FEE_MINIMAL -> {
minFee = CoinEngine.Amount(fee, engine.feeCurrency)
if (rgFee.checkedRadioButtonId == R.id.rbMinimalFee) doSetFee(rgFee.checkedRadioButtonId)
}
ServerApiCommon.ESTIMATE_FEE_NORMAL -> {
normalFee = CoinEngine.Amount(fee, engine.feeCurrency)
if (rgFee.checkedRadioButtonId == R.id.rbNormalFee) doSetFee(rgFee.checkedRadioButtonId)
}
ServerApiCommon.ESTIMATE_FEE_PRIORITY -> {
maxFee = CoinEngine.Amount(fee, engine.feeCurrency)
if (rgFee.checkedRadioButtonId == R.id.rbMaximumFee) doSetFee(rgFee.checkedRadioButtonId)
}
}
etFee.error = null
feeRequestSuccess = true
btnSend.visibility = View.VISIBLE
dtVerified = Date()
}
override fun onFail(message: String?) {
finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_calculate_fee_wrong_data_received_from_node))
}
}
serverApiCommon.setEstimateFee(estimateFeeListener)
// // request estimate fee listener
// val estimateFeeListener: ServerApiCommon.EstimateFeeListener = object : ServerApiCommon.EstimateFeeListener {
// override fun onSuccess(blockCount: Int, estimateFeeResponse: String?) {
// var fee: BigDecimal?
// fee = BigDecimal(estimateFeeResponse) // BTC per 1 kb
//
// if (fee == BigDecimal.ZERO) {
// progressBar.visibility = View.INVISIBLE
// requestEstimateFee()
// }
//
// if (calcSize.toLong() != 0L) {
// fee = fee.multiply(BigDecimal(calcSize.toLong())).divide(BigDecimal(1024)) // per Kb -> per byte
// } else {
// requestEstimateFee()
// }
//
// progressBar.visibility = View.INVISIBLE
//
// fee = fee!!.setScale(8, RoundingMode.DOWN)
//
// when (blockCount) {
// ServerApiCommon.ESTIMATE_FEE_MINIMAL -> {
// minFee = CoinEngine.Amount(fee, engine.feeCurrency)
// if (rgFee.checkedRadioButtonId == R.id.rbMinimalFee) doSetFee(rgFee.checkedRadioButtonId)
// }
//
// ServerApiCommon.ESTIMATE_FEE_NORMAL -> {
// normalFee = CoinEngine.Amount(fee, engine.feeCurrency)
// if (rgFee.checkedRadioButtonId == R.id.rbNormalFee) doSetFee(rgFee.checkedRadioButtonId)
// }
//
// ServerApiCommon.ESTIMATE_FEE_PRIORITY -> {
// maxFee = CoinEngine.Amount(fee, engine.feeCurrency)
// if (rgFee.checkedRadioButtonId == R.id.rbMaximumFee) doSetFee(rgFee.checkedRadioButtonId)
// }
// }
//
// etFee.error = null
// feeRequestSuccess = true
// if (feeRequestSuccess)
//// if (feeRequestSuccess && balanceRequestSuccess)
// btnSend.visibility = View.VISIBLE
// dtVerified = Date()
// }
//
// override fun onFail(message: String?) {
// finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_calculate_fee_wrong_data_received_from_node))
// }
// }
// serverApiCommon.setEstimateFee(estimateFeeListener)
}
public override fun onResume() {
@ -416,131 +415,64 @@ class ConfirmPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
}
// TODO - move to BtcEngine
@Throws(Exception::class)
internal fun buildSize(outputAddress: String, outFee: String, outAmount: String): Int {
val myAddress = ctx.coinData!!.wallet
val pbKey = ctx.card!!.walletPublicKey
val pbComprKey = ctx.card!!.walletPublicKeyRar
// @Throws(Exception::class)
// build script for our address
val rawTxList = (ctx.coinData!! as BtcData).unspentTransactions
val outputScriptWeAreAbleToSpend = Transaction.Script.buildOutput(myAddress).bytes
// private fun requestElectrum(ctx: TangemContext, electrumRequest: ElectrumRequest) {
// if (UtilHelper.isOnline(this)) {
// serverApiElectrum.electrumRequestData(ctx, electrumRequest)
// } else
// finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
// }
// collect unspent
val unspentOutputs = BTCUtils.getOutputs(rawTxList, outputScriptWeAreAbleToSpend)
// private fun requestInfura(method: String) {
// if (UtilHelper.isOnline(this)) {
// serverApiInfura.infura(method, 67, ctx.coinData!!.wallet, "", "")
// } else
// finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
// }
var fullAmount: Long = 0
for (i in unspentOutputs.indices) {
fullAmount += unspentOutputs[i].value
}
// private fun requestEstimateFee() {
// if (calcSize == 0) {
// calcSize = 256
// try {
//
// calcSize = buildSize(etWallet!!.text.toString(), "0.00", etAmount.text.toString())
// } catch (ex: Exception) {
// Log.e("Build Fee error", ex.message)
// }
// }
// serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_PRIORITY)
// serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_NORMAL)
// serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_MINIMAL)
// }
// get first unspent
// val outPut = unspentOutputs[0]
// val outPutIndex = outPut.outputIndex
// get prev TX id;
// val prevTXID = rawTxList[0].txID//"f67b838d6e2c0c587f476f583843e93ff20368eaf96a798bdc25e01f53f8f5d2";
val fees = FormatUtil.ConvertStringToLong(outFee)
var amount = FormatUtil.ConvertStringToLong(outAmount)
amount -= fees
val change = fullAmount - fees - amount
if (amount + fees > fullAmount) {
throw Exception(String.format("Balance (%d) < amount (%d) + (%d)", fullAmount, change, amount))
}
val hashesForSign = arrayOfNulls<ByteArray>(unspentOutputs.size)
for (i in unspentOutputs.indices) {
val newTX = BTCUtils.buildTXForSign(myAddress, outputAddress, myAddress, unspentOutputs, i, amount, change)
val hashData = Util.calculateSHA256(newTX)
val doubleHashData = Util.calculateSHA256(hashData)
// Log.e("TX_BODY_1", BTCUtils.toHex(newTX))
// Log.e("TX_HASH_1", BTCUtils.toHex(hashData))
// Log.e("TX_HASH_2", BTCUtils.toHex(doubleHashData))
// unspentOutputs[i].bodyDoubleHash = doubleHashData
// unspentOutputs[i].bodyHash = hashData
hashesForSign[i] = doubleHashData
}
val signFromCard = ByteArray(64 * unspentOutputs.size)
for (i in unspentOutputs.indices) {
val r = BigInteger(1, Arrays.copyOfRange(signFromCard, 0 + i * 64, 32 + i * 64))
val s = BigInteger(1, Arrays.copyOfRange(signFromCard, 32 + i * 64, 64 + i * 64))
val encodingSign = DerEncodingUtil.packSignDer(r, s, pbKey)
unspentOutputs[i].scriptForBuild = encodingSign
}
val realTX = BTCUtils.buildTXForSend(outputAddress, myAddress, unspentOutputs, amount, change)
return realTX.size
}
private fun requestElectrum(ctx: TangemContext, electrumRequest: ElectrumRequest) {
if( calcSize==0 )
{
calcSize = 256
try {
calcSize = buildSize(etWallet!!.text.toString(), "0.00", etAmount.text.toString())
} catch (ex: Exception) {
Log.e("Build Fee error", ex.message)
}
}
if (UtilHelper.isOnline(this)) {
serverApiElectrum.electrumRequestData(ctx, electrumRequest)
} else
finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
}
private fun requestInfura(method: String) {
if (UtilHelper.isOnline(this)) {
serverApiInfura.infura(method, 67, ctx.coinData!!.wallet, "", "")
} else
finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
}
private fun requestEstimateFee() {
if( calcSize==0 )
{
calcSize = 256
try {
calcSize = buildSize(etWallet!!.text.toString(), "0.00", etAmount.text.toString())
} catch (ex: Exception) {
Log.e("Build Fee error", ex.message)
}
}
serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_PRIORITY)
serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_NORMAL)
serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_MINIMAL)
}
private fun
doSetFee(checkedRadioButtonId: Int) {
private fun doSetFee(checkedRadioButtonId: Int) {
var txtFee = ""
when (checkedRadioButtonId) {
R.id.rbMinimalFee ->
if (minFee != null)
txtFee = minFee!!.toValueString()
else
finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
if (ctx.coinData.minFee != null) {
txtFee = ctx.coinData.minFee!!.toValueString()
btnSend.visibility = View.VISIBLE
}else {
btnSend.visibility = View.INVISIBLE
// finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
}
R.id.rbNormalFee ->
if (normalFee != null)
txtFee = normalFee!!.toValueString()
else
finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
if (ctx.coinData.normalFee != null) {
txtFee = ctx.coinData.normalFee!!.toValueString()
btnSend.visibility = View.VISIBLE
}else {
btnSend.visibility = View.INVISIBLE
// finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
}
R.id.rbMaximumFee ->
if (maxFee != null)
txtFee = maxFee!!.toValueString()
else
finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
if (ctx.coinData.maxFee != null) {
txtFee = ctx.coinData.maxFee!!.toValueString()
btnSend.visibility = View.VISIBLE
}else {
// finishWithError(Activity.RESULT_CANCELED, getString(R.string.cannot_obtain_data_from_blockchain))
btnSend.visibility = View.INVISIBLE
}
}
etFee.setText(txtFee.replace(',', '.'))
}

View file

@ -271,7 +271,7 @@ class MainActivity : AppCompatActivity(), NfcAdapter.ReaderCallback, CardProtoco
} catch (e: Exception) {
e.printStackTrace()
nfcManager!!.notifyReadResult(false)
nfcManager.notifyReadResult(false)
}
}
@ -279,11 +279,11 @@ class MainActivity : AppCompatActivity(), NfcAdapter.ReaderCallback, CardProtoco
super.onResume()
animate()
ReadCardInfoTask.resetLastReadInfo()
nfcManager!!.onResume()
nfcManager.onResume()
}
public override fun onPause() {
nfcManager!!.onPause()
nfcManager.onPause()
if (readCardInfoTask != null) {
readCardInfoTask!!.cancel(true)
}
@ -292,7 +292,7 @@ class MainActivity : AppCompatActivity(), NfcAdapter.ReaderCallback, CardProtoco
public override fun onStop() {
// dismiss enable NFC dialog
nfcManager!!.onStop()
nfcManager.onStop()
if (readCardInfoTask != null) {
readCardInfoTask!!.cancel(true)
}

View file

@ -7,10 +7,6 @@ import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.widget.Toast
import com.tangem.data.network.ElectrumRequest
import com.tangem.data.network.ServerApiElectrum
import com.tangem.data.network.ServerApiInfura
import com.tangem.data.network.model.InfuraResponse
import com.tangem.tangemcard.android.reader.NfcManager
import com.tangem.domain.wallet.*
import com.tangem.domain.wallet.eth.EthData
@ -27,11 +23,11 @@ class SendTransactionActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
const val EXTRA_TX: String = "TX"
}
private var serverApiInfura: ServerApiInfura = ServerApiInfura()
private var serverApiElectrum: ServerApiElectrum = ServerApiElectrum()
// private var serverApiInfura: ServerApiInfura = ServerApiInfura()
// private var serverApiElectrum: ServerApiElectrum = ServerApiElectrum()
private lateinit var ctx: TangemContext
private var tx: String? = null
private var tx: ByteArray? = null
private var nfcManager: NfcManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
@ -43,71 +39,89 @@ class SendTransactionActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
nfcManager = NfcManager(this, this)
ctx = TangemContext.loadFromBundle(this, intent.extras)
tx = intent.getStringExtra(EXTRA_TX)
tx = intent.getByteArrayExtra(EXTRA_TX)
val engine = CoinEngineFactory.create(ctx)
if (ctx.blockchain == Blockchain.Ethereum || ctx.blockchain == Blockchain.EthereumTestNet || ctx.blockchain == Blockchain.Token)
requestInfura(ServerApiInfura.INFURA_ETH_SEND_RAW_TRANSACTION, "")
else if (ctx.blockchain == Blockchain.Bitcoin || ctx.blockchain == Blockchain.BitcoinTestNet)
requestElectrum(ctx, ElectrumRequest.broadcast(ctx.coinData!!.wallet, tx))
else if (ctx.blockchain == Blockchain.BitcoinCash)
requestElectrum(ctx, ElectrumRequest.broadcast(ctx.coinData!!.wallet, tx))
engine!!.requestSendTransaction(
object : CoinEngine.BlockchainRequestsCallbacks {
override fun onComplete(success: Boolean) {
if (success) {
finishWithSuccess()
} else {
finishWithError(this@SendTransactionActivity.getString(R.string.try_again_failed_to_send_transaction))
}
}
override fun onProgress() {
}
override fun allowAdvance(): Boolean {
return UtilHelper.isOnline(this@SendTransactionActivity)
}
},
tx
)
// if (ctx.blockchain == Blockchain.Ethereum || ctx.blockchain == Blockchain.EthereumTestNet || ctx.blockchain == Blockchain.Token)
// requestInfura(ServerApiInfura.INFURA_ETH_SEND_RAW_TRANSACTION, "")
// else if (ctx.blockchain == Blockchain.Bitcoin || ctx.blockchain == Blockchain.BitcoinTestNet)
// requestElectrum(ctx, ElectrumRequest.broadcast(ctx.coinData!!.wallet, tx))
// else if (ctx.blockchain == Blockchain.BitcoinCash)
// requestElectrum(ctx, ElectrumRequest.broadcast(ctx.coinData!!.wallet, tx))
// request electrum listener
val electrumBodyListener: ServerApiElectrum.ElectrumRequestDataListener = object : ServerApiElectrum.ElectrumRequestDataListener {
override fun onSuccess(electrumRequest: ElectrumRequest?) {
if (electrumRequest!!.isMethod(ElectrumRequest.METHOD_SendTransaction)) {
try {
if (electrumRequest.resultString.isNullOrEmpty())
finishWithError("Rejected by node: " + electrumRequest.getError())
else
finishWithSuccess()
}
catch (e: Exception)
{
if( e.message!=null )
{
finishWithError(e.message!!)
}else{
finishWithError(e.javaClass.name)
}
}
}
}
override fun onFail(message: String?) {
finishWithError(message!!)
}
}
serverApiElectrum.setElectrumRequestData(electrumBodyListener)
// val electrumBodyListener: ServerApiElectrum.ElectrumRequestDataListener = object : ServerApiElectrum.ElectrumRequestDataListener {
// override fun onSuccess(electrumRequest: ElectrumRequest?) {
// if (electrumRequest!!.isMethod(ElectrumRequest.METHOD_SendTransaction)) {
// try {
// if (electrumRequest.resultString.isNullOrEmpty())
// finishWithError("Rejected by node: " + electrumRequest.getError())
// else
// finishWithSuccess()
// } catch (e: Exception) {
// if (e.message != null) {
// finishWithError(e.message!!)
// } else {
// finishWithError(e.javaClass.name)
// }
// }
// }
// }
//
// override fun onFail(message: String?) {
// finishWithError(message!!)
// }
// }
// serverApiElectrum.setElectrumRequestData(electrumBodyListener)
// request infura listener
val infuraBodyListener: ServerApiInfura.InfuraBodyListener = object : ServerApiInfura.InfuraBodyListener {
override fun onSuccess(method: String, infuraResponse: InfuraResponse) {
when (method) {
ServerApiInfura.INFURA_ETH_SEND_RAW_TRANSACTION -> {
if (infuraResponse.result.isEmpty())
finishWithError("Rejected by node: " + infuraResponse.error)
else {
val nonce = (ctx.coinData!! as EthData).confirmedTXCount
nonce.add(BigInteger.valueOf(1))
(ctx.coinData!! as EthData).confirmedTXCount = nonce
finishWithSuccess()
}
}
}
}
override fun onFail(method: String, message: String) {
when (method) {
ServerApiInfura.INFURA_ETH_SEND_RAW_TRANSACTION -> {
finishWithError(message)
}
}
}
}
serverApiInfura.setInfuraResponse(infuraBodyListener)
// val infuraBodyListener: ServerApiInfura.InfuraBodyListener = object : ServerApiInfura.InfuraBodyListener {
// override fun onSuccess(method: String, infuraResponse: InfuraResponse) {
// when (method) {
// ServerApiInfura.INFURA_ETH_SEND_RAW_TRANSACTION -> {
// if (infuraResponse.result.isEmpty())
// finishWithError("Rejected by node: " + infuraResponse.error)
// else {
// val nonce = (ctx.coinData!! as EthData).confirmedTXCount
// nonce.add(BigInteger.valueOf(1))
// (ctx.coinData!! as EthData).confirmedTXCount = nonce
// finishWithSuccess()
// }
// }
// }
// }
//
// override fun onFail(method: String, message: String) {
// when (method) {
// ServerApiInfura.INFURA_ETH_SEND_RAW_TRANSACTION -> {
// finishWithError(message)
// }
// }
// }
// }
// serverApiInfura.setInfuraResponse(infuraBodyListener)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
@ -143,20 +157,20 @@ class SendTransactionActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
}
}
private fun requestInfura(method: String, contract: String) {
if (UtilHelper.isOnline(this)) {
serverApiInfura.infura(method, 67, ctx.coinData!!.wallet, contract, tx)
} else
finishWithError(getString(R.string.no_connection))
}
private fun requestElectrum(ctx: TangemContext, electrumRequest: ElectrumRequest) {
if (UtilHelper.isOnline(this)) {
serverApiElectrum.electrumRequestData(ctx, electrumRequest)
} else
finishWithError(getString(R.string.no_connection))
}
// private fun requestInfura(method: String, contract: String) {
// if (UtilHelper.isOnline(this)) {
// serverApiInfura.infura(method, 67, ctx.coinData!!.wallet, contract, tx)
// } else
// finishWithError(getString(R.string.no_connection))
// }
// private fun requestElectrum(ctx: TangemContext, electrumRequest: ElectrumRequest) {
// if (UtilHelper.isOnline(this)) {
// serverApiElectrum.electrumRequestData(ctx, electrumRequest)
// } else
// finishWithError(getString(R.string.no_connection))
// }
//
private fun finishWithSuccess() {
val intent = Intent()
intent.putExtra("message", getString(R.string.transaction_has_been_successfully_signed))

View file

@ -144,4 +144,143 @@ class SignPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback, Card
?: throw CardProtocol.TangemException("Can't create CoinEngine!")
coinEngine.setOnNeedSendPayment { tx ->
if (tx != null) {
// [REDACTED_TODO_COMMENT]
val intent = Intent(this, SendTransactionActivity::class.java)
ctx.saveToIntent(intent)
intent.putExtra(SendTransactionActivity.EXTRA_TX, tx)
startActivityForResult(intent, SignPaymentActivity.REQUEST_CODE_SEND_PAYMENT)
}
}
val paymentToSign = coinEngine.constructPayment(amount, fee, isIncludeFee, outAddressStr)
signPaymentTask = SignTask(ctx.card, NfcReader(nfcManager, isoDep), App.localStorage, App.pinStorage, this, paymentToSign)
signPaymentTask!!.start()
} else {
// Log.d(TAG, "Mismatch card UID (" + sUID + " instead of " + card!!.uid + ")")
nfcManager!!.ignoreTag(isoDep.tag)
}
}catch (e: CardProtocol.TangemException_WrongAmount)
{
try {
val intent = Intent()
intent.putExtra("message", getString(R.string.cannot_sign_transaction_wrong_amount))
intent.putExtra("UID", ctx.card.uid)
intent.putExtra("Card", ctx.card.asBundle)
setResult(Activity.RESULT_CANCELED, intent)
finish()
} catch (e: Exception) {
e.printStackTrace()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onReadStart(cardProtocol: CardProtocol) {
progressBar!!.post {
progressBar!!.visibility = View.VISIBLE
progressBar!!.progress = 5
}
}
override fun onReadProgress(protocol: CardProtocol, progress: Int) {
progressBar!!.post { progressBar!!.progress = progress }
}
override fun onReadFinish(cardProtocol: CardProtocol?) {
signPaymentTask = null
if (cardProtocol != null) {
if (cardProtocol.error == null) {
progressBar!!.post {
progressBar!!.progress = 100
progressBar!!.progressTintList = ColorStateList.valueOf(Color.GREEN)
}
} else {
lastReadSuccess = false
if (cardProtocol.error.javaClass == CardProtocol.TangemException_InvalidPIN::class.java) {
progressBar!!.post {
progressBar!!.progress = 100
progressBar!!.progressTintList = ColorStateList.valueOf(Color.RED)
}
progressBar!!.postDelayed({
try {
progressBar!!.progress = 0
progressBar!!.progressTintList = ColorStateList.valueOf(Color.DKGRAY)
progressBar!!.visibility = View.INVISIBLE
val intent = Intent()
intent.putExtra("message", getString(R.string.cannot_sign_transaction__make_sure_you_enter_correct_pin_2))
intent.putExtra("UID", cardProtocol.card.uid)
intent.putExtra("Card", cardProtocol.card.asBundle)
setResult(RESULT_INVALID_PIN, intent)
finish()
} catch (e: Exception) {
e.printStackTrace()
}
}, 500)
} else {
if (cardProtocol.error is CardProtocol.TangemException_WrongAmount) {
try {
val intent = Intent()
intent.putExtra("message", getString(R.string.cannot_sign_transaction_wrong_amount))
intent.putExtra("UID", cardProtocol.card.uid)
intent.putExtra("Card", cardProtocol.card.asBundle)
setResult(Activity.RESULT_CANCELED, intent)
finish()
} catch (e: Exception) {
e.printStackTrace()
}
}
progressBar!!.post {
if (cardProtocol.error is CardProtocol.TangemException_ExtendedLengthNotSupported) {
if (!NoExtendedLengthSupportDialog.allReadyShowed) {
NoExtendedLengthSupportDialog.message = getText(R.string.the_nfc_adapter_length_apdu).toString() + "\n" + getText(R.string.the_nfc_adapter_length_apdu_advice).toString()
NoExtendedLengthSupportDialog().show(supportFragmentManager, NoExtendedLengthSupportDialog.TAG)
}
} else {
Toast.makeText(baseContext, R.string.try_to_scan_again, Toast.LENGTH_LONG).show()
}
progressBar!!.progress = 100
progressBar!!.progressTintList = ColorStateList.valueOf(Color.RED)
}
}
}
}
progressBar!!.postDelayed({
try {
progressBar!!.progress = 0
progressBar!!.progressTintList = ColorStateList.valueOf(Color.DKGRAY)
progressBar!!.visibility = View.INVISIBLE
} catch (e: Exception) {
e.printStackTrace()
}
}, 500)
}
override fun onReadCancel() {
signPaymentTask = null
progressBar!!.postDelayed({
try {
progressBar!!.progress = 0
progressBar!!.progressTintList = ColorStateList.valueOf(Color.DKGRAY)
progressBar!!.visibility = View.INVISIBLE
} catch (e: Exception) {
e.printStackTrace()
}
}, 500)
}
override fun onReadWait(msec: Int) {
WaitSecurityDelayDialog.OnReadWait(this, msec)
}
override fun onReadBeforeRequest(timeout: Int) {
WaitSecurityDelayDialog.onReadBeforeRequest(this, timeout)
}
override fun onReadAfterRequest() {
WaitSecurityDelayDialog.onReadAfterRequest(this)
}
}

View file

@ -22,20 +22,11 @@ import android.widget.Toast
import com.tangem.App
import com.tangem.Constant
import com.tangem.data.Blockchain
import com.tangem.data.network.ElectrumRequest
import com.tangem.data.network.ServerApiCommon
import com.tangem.data.network.ServerApiElectrum
import com.tangem.data.network.ServerApiInfura
import com.tangem.data.network.model.InfuraResponse
import com.tangem.domain.wallet.BalanceValidator
import com.tangem.domain.wallet.CoinEngine
import com.tangem.domain.wallet.CoinEngineFactory
import com.tangem.domain.wallet.TangemContext
import com.tangem.domain.wallet.bch.BtcCashEngine
import com.tangem.domain.wallet.btc.BtcData
import com.tangem.domain.wallet.eth.EthData
import com.tangem.domain.wallet.token.TokenData
import com.tangem.domain.wallet.token.TokenEngine
import com.tangem.presentation.activity.*
import com.tangem.presentation.dialog.NoExtendedLengthSupportDialog
import com.tangem.presentation.dialog.PINSwapWarningDialog
@ -55,9 +46,7 @@ import com.tangem.tangemserver.android.model.CardVerifyAndGetInfo
import com.tangem.util.UtilHelper
import com.tangem.wallet.R
import kotlinx.android.synthetic.main.fr_loaded_wallet.*
import org.json.JSONException
import java.io.InputStream
import java.math.BigInteger
import java.util.*
class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notifications, SharedPreferences.OnSharedPreferenceChangeListener {
@ -68,8 +57,6 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
private lateinit var nfcManager: NfcManager
private var serverApiCommon: ServerApiCommon = ServerApiCommon()
private var serverApiInfura: ServerApiInfura = ServerApiInfura()
private var serverApiElectrum: ServerApiElectrum = ServerApiElectrum()
private var serverApiTangem: ServerApiTangem = ServerApiTangem()
private var singleToast: Toast? = null
@ -85,7 +72,17 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
private var cardProtocol: CardProtocol? = null
private val inactiveColor: ColorStateList by lazy { resources.getColorStateList(R.color.btn_dark) }
private val activeColor: ColorStateList by lazy { resources.getColorStateList(R.color.colorAccent) }
private var requestCounter = 0
private var requestCounter: Int = 0
set(value)
{
field=value
Log.i(TAG, "requestCounter, set $field")
if (field <= 0 && srl!=null && srl.isRefreshing ) {
Log.e(TAG, "+++++++++++ FINISH REFRESH")
if (srl != null) srl!!.isRefreshing = false
//updateViews()
}
}
private var timerRepeatRefresh: Timer? = null
override fun onCreate(savedInstanceState: Bundle?) {
@ -114,10 +111,6 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
btnExtract.isEnabled = false
btnExtract.backgroundTintList = inactiveColor
refresh()
startVerify(lastTag)
tvWallet.text = ctx.coinData.wallet
// set listeners
@ -193,7 +186,6 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
if (cardProtocol != null)
// openVerifyCard(cardProtocol!!)
(activity as LoadedWalletActivity).navigator.showVerifyCard(context as Activity, ctx)
else
showSingleToast(R.string.need_attach_card_again)
}
@ -206,213 +198,215 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
else if (ctx.card!!.remainingSignatures == 0)
showSingleToast(R.string.card_has_no_remaining_signature)
else {
(activity as LoadedWalletActivity).navigator.showPreparePayment(context as Activity, ctx)
// val intent = Intent(activity, PreparePaymentActivity::class.java)
// ctx.saveToIntent(intent)
// startActivityForResult(intent, Constant.REQUEST_CODE_SEND_PAYMENT)
val intent = Intent(activity, PreparePaymentActivity::class.java)
ctx.saveToIntent(intent)
startActivityForResult(intent, Constant.REQUEST_CODE_SEND_PAYMENT)
}
} else
Toast.makeText(activity, getString(R.string.no_connection), Toast.LENGTH_SHORT).show()
}
// request electrum listener
val electrumBodyListener: ServerApiElectrum.ElectrumRequestDataListener = object : ServerApiElectrum.ElectrumRequestDataListener {
override fun onSuccess(electrumRequest: ElectrumRequest?) {
if (electrumRequest!!.isMethod(ElectrumRequest.METHOD_GetBalance)) {
try {
val walletAddress = electrumRequest.params.getString(0)
val confBalance = electrumRequest.result.getLong("confirmed")
val unconfirmedBalance = electrumRequest.result.getLong("unconfirmed")
ctx.coinData!!.isBalanceReceived = true
(ctx.coinData!! as BtcData).setBalanceConfirmed(confBalance)
(ctx.coinData!! as BtcData).balanceUnconfirmed = unconfirmedBalance
(ctx.coinData!! as BtcData).validationNodeDescription = serverApiElectrum.validationNodeDescription
} catch (e: JSONException) {
e.printStackTrace()
Log.e(TAG, "FAIL METHOD_GetBalance JSONException")
}
}
if (electrumRequest.isMethod(ElectrumRequest.METHOD_ListUnspent)) {
try {
val walletAddress = electrumRequest.params.getString(0)
val jsUnspentArray = electrumRequest.resultArray
try {
(ctx.coinData!! as BtcData).unspentTransactions.clear()
for (i in 0 until jsUnspentArray.length()) {
val jsUnspent = jsUnspentArray.getJSONObject(i)
val trUnspent = BtcData.UnspentTransaction()
trUnspent.txID = jsUnspent.getString("tx_hash")
trUnspent.Amount = jsUnspent.getInt("value")
trUnspent.Height = jsUnspent.getInt("height")
(ctx.coinData!! as BtcData).unspentTransactions.add(trUnspent)
}
} catch (e: JSONException) {
e.printStackTrace()
Log.e(TAG, "FAIL METHOD_ListUnspent JSONException")
}
for (i in 0 until jsUnspentArray.length()) {
val jsUnspent = jsUnspentArray.getJSONObject(i)
val height = jsUnspent.getInt("height")
val hash = jsUnspent.getString("tx_hash")
if (height != -1) {
requestElectrum(ElectrumRequest.getTransaction(walletAddress, hash))
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
if (electrumRequest.isMethod(ElectrumRequest.METHOD_GetTransaction)) {
try {
val txHash = electrumRequest.txHash
val raw = electrumRequest.resultString
val listTx = (ctx.coinData!! as BtcData).unspentTransactions
for (tx in listTx) {
if (tx.txID == txHash)
tx.Raw = raw
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
if (electrumRequest.isMethod(ElectrumRequest.METHOD_SendTransaction)) {
}
counterMinus()
}
override fun onFail(method: String?) {
}
}
serverApiElectrum.setElectrumRequestData(electrumBodyListener)
// request infura listener
val infuraBodyListener: ServerApiInfura.InfuraBodyListener = object : ServerApiInfura.InfuraBodyListener {
override fun onSuccess(method: String, infuraResponse: InfuraResponse) {
when (method) {
ServerApiInfura.INFURA_ETH_GET_BALANCE -> {
var balanceCap = infuraResponse.result
balanceCap = balanceCap.substring(2)
val l = BigInteger(balanceCap, 16)
// val d = l.divide(BigInteger("1000000000000000000", 10))
// val balance = d.toLong()
// (ctx.coinData!! as EthData).setBalanceConfirmed(balance)
// (ctx.coinData!! as EthData).balanceUnconfirmed = 0L
if (ctx.blockchain != Blockchain.Token) {
(ctx.coinData!! as EthData).isBalanceReceived = true
(ctx.coinData!! as EthData).balanceInInternalUnits = CoinEngine.InternalAmount(l.toBigDecimal(), "wei")
} else {
(ctx.coinData!! as TokenData).isBalanceReceived = true
//(ctx.coinData!! as TokenData).balanceInInternalUnits = CoinEngine.InternalAmount(l.toBigDecimal(),ctx.card.tokenSymbol)
(ctx.coinData!! as TokenData).balanceAlterInInternalUnits = CoinEngine.InternalAmount(l.toBigDecimal(), "wei")
}
// Log.i("$TAG eth_get_balance", balanceCap)
}
ServerApiInfura.INFURA_ETH_GET_TRANSACTION_COUNT -> {
var nonce = infuraResponse.result
nonce = nonce.substring(2)
val count = BigInteger(nonce, 16)
(ctx.coinData!! as EthData).confirmedTXCount = count
// Log.i("$TAG eth_getTransCount", nonce)
}
ServerApiInfura.INFURA_ETH_GET_PENDING_COUNT -> {
var pending = infuraResponse.result
pending = pending.substring(2)
val count = BigInteger(pending, 16)
(ctx.coinData!! as EthData).unconfirmedTXCount = count
// Log.i("$TAG eth_getPendingTxCount", pending)
}
ServerApiInfura.INFURA_ETH_CALL -> {
try {
var balanceCap = infuraResponse.result
balanceCap = balanceCap.substring(2)
val l = BigInteger(balanceCap, 16)
val balance = l.toLong()
// if (l.compareTo(BigInteger.ZERO) == 0) {
// //ctx.card!!.blockchainID = Blockchain.Ethereum.id
// ctx.card!!.addTokenToBlockchainName()
// val electrumBodyListener: ServerApiElectrum.ElectrumRequestDataListener = object : ServerApiElectrum.ElectrumRequestDataListener {
// override fun onSuccess(electrumRequest: ElectrumRequest?) {
// if (electrumRequest!!.isMethod(ElectrumRequest.METHOD_GetBalance)) {
// try {
// val walletAddress = electrumRequest.params.getString(0)
// val confBalance = electrumRequest.result.getLong("confirmed")
// val unconfirmedBalance = electrumRequest.result.getLong("unconfirmed")
// ctx.coinData!!.isBalanceReceived = true
// (ctx.coinData!! as BtcData).setBalanceConfirmed(confBalance)
// (ctx.coinData!! as BtcData).balanceUnconfirmed = unconfirmedBalance
// (ctx.coinData!! as BtcData).validationNodeDescription = serverApiElectrum.validationNodeDescription
// } catch (e: JSONException) {
// e.printStackTrace()
// Log.e(TAG, "FAIL METHOD_GetBalance JSONException")
// }
// }
//
// //TODO check
// //ctx.blockchain=lBlockchain.Ethereum
// if (electrumRequest.isMethod(ElectrumRequest.METHOD_ListUnspent)) {
// try {
// val walletAddress = electrumRequest.params.getString(0)
// val jsUnspentArray = electrumRequest.resultArray
// try {
// (ctx.coinData!! as BtcData).unspentTransactions.clear()
// for (i in 0 until jsUnspentArray.length()) {
// val jsUnspent = jsUnspentArray.getJSONObject(i)
// val trUnspent = BtcData.UnspentTransaction()
// trUnspent.txID = jsUnspent.getString("tx_hash")
// trUnspent.Amount = jsUnspent.getInt("value")
// trUnspent.Height = jsUnspent.getInt("height")
// (ctx.coinData!! as BtcData).unspentTransactions.add(trUnspent)
// }
// } catch (e: JSONException) {
// e.printStackTrace()
// Log.e(TAG, "FAIL METHOD_ListUnspent JSONException")
// }
//
// requestCounter--
// if (requestCounter == 0) srl!!.isRefreshing = false
// for (i in 0 until jsUnspentArray.length()) {
// val jsUnspent = jsUnspentArray.getJSONObject(i)
// val height = jsUnspent.getInt("height")
// val hash = jsUnspent.getString("tx_hash")
// if (height != -1) {
// requestElectrum(ElectrumRequest.getTransaction(walletAddress, hash))
// }
// }
// } catch (e: JSONException) {
// e.printStackTrace()
// }
// }
//
// requestInfura(ServerApiCommon.INFURA_ETH_GET_BALANCE, "")
// requestInfura(ServerApiCommon.INFURA_ETH_GET_TRANSACTION_COUNT, "")
// requestInfura(ServerApiCommon.INFURA_ETH_GET_PENDING_COUNT, "")
// if (electrumRequest.isMethod(ElectrumRequest.METHOD_GetTransaction)) {
// try {
// val txHash = electrumRequest.txHash
// val raw = electrumRequest.resultString
// val listTx = (ctx.coinData!! as BtcData).unspentTransactions
// for (tx in listTx) {
// if (tx.txID == txHash)
// tx.Raw = raw
// }
// } catch (e: JSONException) {
// e.printStackTrace()
// }
// }
//
// if (electrumRequest.isMethod(ElectrumRequest.METHOD_SendTransaction)) {
//
// }
//
// counterMinus()
// }
//
// override fun onFail(method: String?) {
//
// }
// }
// serverApiElectrum.setElectrumRequestData(electrumBodyListener)
// // request infura listener
// val infuraBodyListener: ServerApiInfura.InfuraBodyListener = object : ServerApiInfura.InfuraBodyListener {
// override fun onSuccess(method: String, infuraResponse: InfuraResponse) {
// when (method) {
// ServerApiInfura.INFURA_ETH_GET_BALANCE -> {
// var balanceCap = infuraResponse.result
// balanceCap = balanceCap.substring(2)
// val l = BigInteger(balanceCap, 16)
//// val d = l.divide(BigInteger("1000000000000000000", 10))
//// val balance = d.toLong()
//
//// (ctx.coinData!! as EthData).setBalanceConfirmed(balance)
//// (ctx.coinData!! as EthData).balanceUnconfirmed = 0L
// if (ctx.blockchain != Blockchain.Token) {
// (ctx.coinData!! as EthData).isBalanceReceived = true
// (ctx.coinData!! as EthData).balanceInInternalUnits = CoinEngine.InternalAmount(l.toBigDecimal(), "wei")
// } else {
// (ctx.coinData!! as TokenData).isBalanceReceived = true
// //(ctx.coinData!! as TokenData).balanceInInternalUnits = CoinEngine.InternalAmount(l.toBigDecimal(),ctx.card.tokenSymbol)
// (ctx.coinData!! as TokenData).balanceAlterInInternalUnits = CoinEngine.InternalAmount(l.toBigDecimal(), "wei")
// }
//
//// Log.i("$TAG eth_get_balance", balanceCap)
// }
//
// ServerApiInfura.INFURA_ETH_GET_TRANSACTION_COUNT -> {
// var nonce = infuraResponse.result
// nonce = nonce.substring(2)
// val count = BigInteger(nonce, 16)
// (ctx.coinData!! as EthData).confirmedTXCount = count
//
//
//// Log.i("$TAG eth_getTransCount", nonce)
// }
//
// ServerApiInfura.INFURA_ETH_GET_PENDING_COUNT -> {
// var pending = infuraResponse.result
// pending = pending.substring(2)
// val count = BigInteger(pending, 16)
// (ctx.coinData!! as EthData).unconfirmedTXCount = count
//
//// Log.i("$TAG eth_getPendingTxCount", pending)
// }
//
// ServerApiInfura.INFURA_ETH_CALL -> {
// try {
// var balanceCap = infuraResponse.result
// balanceCap = balanceCap.substring(2)
// val l = BigInteger(balanceCap, 16)
// val balance = l.toLong()
//// if (l.compareTo(BigInteger.ZERO) == 0) {
//// //ctx.card!!.blockchainID = Blockchain.Ethereum.id
//// ctx.card!!.addTokenToBlockchainName()
////
//// //TODO check
//// //ctx.blockchain=lBlockchain.Ethereum
////
//// requestCounter--
//// if (requestCounter == 0) srl!!.isRefreshing = false
////
//// requestInfura(ServerApiCommon.INFURA_ETH_GET_BALANCE, "")
//// requestInfura(ServerApiCommon.INFURA_ETH_GET_TRANSACTION_COUNT, "")
//// requestInfura(ServerApiCommon.INFURA_ETH_GET_PENDING_COUNT, "")
//// return
//// }
// (ctx.coinData!! as EthData).balanceInInternalUnits = CoinEngine.InternalAmount(l.toBigDecimal(), ctx.card.tokenSymbol)
//
//// Log.i("$TAG eth_call", balanceCap)
//
// requestInfura(ServerApiInfura.INFURA_ETH_GET_BALANCE, "")
// requestInfura(ServerApiInfura.INFURA_ETH_GET_TRANSACTION_COUNT, "")
// requestInfura(ServerApiInfura.INFURA_ETH_GET_PENDING_COUNT, "")
// } catch (e: JSONException) {
// e.printStackTrace()
// } catch (e: NumberFormatException) {
// e.printStackTrace()
// } catch (e: Exception) {
// e.printStackTrace()
// }
// }
//
// ServerApiInfura.INFURA_ETH_SEND_RAW_TRANSACTION -> {
// try {
// var hashTX: String
// try {
// val tmp = infuraResponse.result
// hashTX = tmp
// } catch (e: JSONException) {
// return
// }
(ctx.coinData!! as EthData).balanceInInternalUnits = CoinEngine.InternalAmount(l.toBigDecimal(), ctx.card.tokenSymbol)
// Log.i("$TAG eth_call", balanceCap)
requestInfura(ServerApiInfura.INFURA_ETH_GET_BALANCE, "")
requestInfura(ServerApiInfura.INFURA_ETH_GET_TRANSACTION_COUNT, "")
requestInfura(ServerApiInfura.INFURA_ETH_GET_PENDING_COUNT, "")
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: NumberFormatException) {
e.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
}
}
ServerApiInfura.INFURA_ETH_SEND_RAW_TRANSACTION -> {
try {
var hashTX: String
try {
val tmp = infuraResponse.result
hashTX = tmp
} catch (e: JSONException) {
return
}
if (hashTX.startsWith("0x") || hashTX.startsWith("0X")) {
hashTX = hashTX.substring(2)
}
Log.e("$TAG TX_RESULT", hashTX)
val nonce = (ctx.coinData!! as EthData).confirmedTXCount
nonce.add(BigInteger.valueOf(1))
(ctx.coinData!! as EthData).confirmedTXCount = nonce
Log.e("$TAG TX_RESULT", hashTX)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
counterMinus()
}
override fun onFail(method: String, message: String) {
}
}
serverApiInfura.setInfuraResponse(infuraBodyListener)
//
// if (hashTX.startsWith("0x") || hashTX.startsWith("0X")) {
// hashTX = hashTX.substring(2)
// }
//
// Log.e("$TAG TX_RESULT", hashTX)
//
// val nonce = (ctx.coinData!! as EthData).confirmedTXCount
// nonce.add(BigInteger.valueOf(1))
// (ctx.coinData!! as EthData).confirmedTXCount = nonce
//
// Log.e("$TAG TX_RESULT", hashTX)
//
// } catch (e: Exception) {
// e.printStackTrace()
// }
// }
// }
//
// counterMinus()
// }
//
// override fun onFail(method: String, message: String) {
//
// }
// }
// serverApiInfura.setInfuraResponse(infuraBodyListener)
// request card verify and get info listener
val cardVerifyAndGetInfoListener: ServerApiTangem.CardVerifyAndGetInfoListener = object : ServerApiTangem.CardVerifyAndGetInfoListener {
override fun onSuccess(cardVerifyAndGetArtworkResponse: CardVerifyAndGetInfo.Response?) {
Log.i(TAG,"cardVerifyAndGetInfoListener onSuccess")
if( activity==null || !UtilHelper.isOnline(activity!!)) return
val result = cardVerifyAndGetArtworkResponse?.results!![0]
if (result.error != null) {
ctx.card!!.isOnlineVerified = false
@ -420,7 +414,10 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
}
ctx.card!!.isOnlineVerified = result.passed
if (requestCounter == 0) updateViews()
requestCounter--
// if (requestCounter == 0)
updateViews()
if (!result.passed) return
@ -428,17 +425,11 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
Log.w(TAG, "Batch ${result.batch} info changed to '$result'")
ivTangemCard.setImageBitmap(App.localStorage.getCardArtworkBitmap(ctx.card!!))
App.localStorage.applySubstitution(ctx.card!!)
//todo - check this is not need after refactoring
// if (ctx.blockchain == Blockchain.Token || ctx.blockchain == Blockchain.Ethereum) {
// ctx.card!!.setBlockchainIDFromCard(Blockchain.Ethereum.id)
//ctx.blockchain=Blockchain.Ethereum
//engine=engine!!.swithToOtherEngine(Blockchain.Ethereum)
// }
refresh()
}
if (result.artwork != null && App.localStorage.checkNeedUpdateArtwork(result.artwork)) {
Log.w(TAG, "Artwork '${result.artwork!!.id}' updated, need download")
requestCounter++
serverApiTangem.requestArtwork(result.artwork!!.id, result.artwork!!.getUpdateDate(), ctx.card!!)
updateViews()
}
@ -446,7 +437,10 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
}
override fun onFail(message: String?) {
Log.i(TAG,"cardVerifyAndGetInfoListener onFail")
if( activity==null || !UtilHelper.isOnline(activity!!)) return
requestCounter--
updateViews()
}
}
serverApiTangem.setCardVerifyAndGetInfoListener(cardVerifyAndGetInfoListener)
@ -454,47 +448,51 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
// request artwork listener
val artworkListener: ServerApiTangem.ArtworkListener = object : ServerApiTangem.ArtworkListener {
override fun onSuccess(artworkId: String?, inputStream: InputStream?, updateDate: Date?) {
Log.i(TAG,"artworkListener onSuccess")
if( activity==null || !UtilHelper.isOnline(activity!!)) return
App.localStorage.updateArtwork(artworkId!!, inputStream!!, updateDate!!)
requestCounter--
ivTangemCard.setImageBitmap(App.localStorage.getCardArtworkBitmap(ctx.card!!))
updateViews()
}
override fun onFail(message: String?) {
Log.i(TAG,"artworkListener onFail")
if( activity==null || !UtilHelper.isOnline(activity!!)) return
requestCounter--
updateViews()
}
}
serverApiTangem.setArtworkListener(artworkListener)
// request rate info listener
serverApiCommon.setRateInfoData {
if( activity==null || !UtilHelper.isOnline(activity!!)) return@setRateInfoData
val rate = it.priceUsd.toFloat()
ctx.coinData!!.rate = rate
ctx.coinData!!.rateAlter = rate
}
}
private fun counterMinus() {
requestCounter--
if (requestCounter == 0) {
if (srl != null) srl!!.isRefreshing = false
updateViews()
}
refresh()
startVerify(lastTag)
}
override fun onResume() {
super.onResume()
nfcManager!!.onResume()
nfcManager.onResume()
}
override fun onPause() {
super.onPause()
nfcManager!!.onPause()
nfcManager.onPause()
if (timerRepeatRefresh != null)
timerRepeatRefresh!!.cancel()
}
override fun onStop() {
super.onStop()
nfcManager!!.onStop()
nfcManager.onStop()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
@ -727,17 +725,19 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
}
fun updateViews() {
if( activity==null || !UtilHelper.isOnline(activity!!)) return
if (timerHideErrorAndMessage != null) {
timerHideErrorAndMessage!!.cancel()
timerHideErrorAndMessage = null
}
if (ctx.error == null || ctx.error.isEmpty()) {
tvError.visibility = View.GONE
tvError.text = ""
} else {
if (ctx.hasError()) {
tvError.visibility = View.VISIBLE
tvError.text = ctx.error
} else {
tvError.visibility = View.GONE
tvError.text = ""
}
if (ctx.message == null || ctx.message.isEmpty()) {
@ -785,7 +785,7 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
} else
tvBlockchain.text = ctx.blockchainName
if (engine.hasBalanceInfo()) {
if (requestCounter==0 && engine.hasBalanceInfo()) {
btnExtract.isEnabled = true
btnExtract.backgroundTintList = activeColor
} else {
@ -793,95 +793,131 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
btnExtract.backgroundTintList = inactiveColor
}
ctx.error = null
ctx.message = null
//TODO why ???
// ctx.error = null
// ctx.message = null
}
private fun refresh() {
if (ctx.card == null) return
// clear all card data and request again
srl?.isRefreshing = true
ctx.coinData.clearInfo()
ctx.error = null
ctx.message = null
Log.e(TAG, "============= START REFRESH")
requestCounter = 0
srl?.isRefreshing = true
updateViews()
requestVerifyAndGetInfo()
val coinEngine = CoinEngineFactory.create(ctx)
requestCounter++
coinEngine!!.requestBalanceAndUnspentTransactions(
object : CoinEngine.BlockchainRequestsCallbacks {
override fun onComplete(success: Boolean) {
Log.i(TAG, "requestBalanceAndUnspentTransactions onComplete: "+success.toString()+", request counter "+requestCounter.toString())
if( activity==null || !UtilHelper.isOnline(activity!!)) return
requestCounter--
if(! success)
{
Log.e(TAG, "ctx.error: "+ctx.error)
}
updateViews()
}
override fun onProgress() {
if( activity==null || !UtilHelper.isOnline(activity!!)) return
Log.i(TAG, "requestBalanceAndUnspentTransactions onProgress")
updateViews()
}
override fun allowAdvance(): Boolean {
return UtilHelper.isOnline(context as Activity)
}
}
)
// Bitcoin
if (ctx.blockchain == Blockchain.Bitcoin || ctx.blockchain == Blockchain.BitcoinTestNet) {
ctx.coinData.setIsBalanceEqual(true)
requestElectrum(ElectrumRequest.checkBalance(ctx.coinData!!.wallet))
requestElectrum(ElectrumRequest.listUnspent(ctx.coinData!!.wallet))
// requestElectrum(ElectrumRequest.checkBalance(ctx.coinData!!.wallet))
// requestElectrum(ElectrumRequest.listUnspent(ctx.coinData!!.wallet))
requestRateInfo("bitcoin")
}
// BitcoinCash
else if (ctx.blockchain == Blockchain.BitcoinCash) {
ctx.coinData.setIsBalanceEqual(true)
val engine = CoinEngineFactory.create(ctx)
requestElectrum(ElectrumRequest.checkBalance((engine as BtcCashEngine).convertToLegacyAddress(ctx.coinData!!.wallet)))
requestElectrum(ElectrumRequest.listUnspent(engine.convertToLegacyAddress(ctx.coinData!!.wallet)))
// val engine = CoinEngineFactory.create(ctx)
//
// requestElectrum(ElectrumRequest.checkBalance((engine as BtcCashEngine).convertToLegacyAddress(ctx.coinData!!.wallet)))
// requestElectrum(ElectrumRequest.listUnspent(engine.convertToLegacyAddress(ctx.coinData!!.wallet)))
requestRateInfo("bitcoin-cash")
}
// Ethereum
else if (ctx.blockchain == Blockchain.Ethereum || ctx.blockchain == Blockchain.EthereumTestNet) {
requestInfura(ServerApiInfura.INFURA_ETH_GET_BALANCE, "")
requestInfura(ServerApiInfura.INFURA_ETH_GET_TRANSACTION_COUNT, "")
requestInfura(ServerApiInfura.INFURA_ETH_GET_PENDING_COUNT, "")
// requestInfura(ServerApiInfura.INFURA_ETH_GET_BALANCE, "")
// requestInfura(ServerApiInfura.INFURA_ETH_GET_TRANSACTION_COUNT, "")
// requestInfura(ServerApiInfura.INFURA_ETH_GET_PENDING_COUNT, "")
requestRateInfo("ethereum")
}
// Token
else if (ctx.blockchain == Blockchain.Token) {
val engine = CoinEngineFactory.create(ctx)
requestInfura(ServerApiInfura.INFURA_ETH_CALL, (engine as TokenEngine).getContractAddress(ctx.card))
// val engine = CoinEngineFactory.create(ctx)
// requestInfura(ServerApiInfura.INFURA_ETH_CALL, (engine as TokenEngine).getContractAddress(ctx.card))
requestRateInfo("ethereum")
}
}
private fun requestElectrum(electrumRequest: ElectrumRequest) {
if (UtilHelper.isOnline(context as Activity)) {
requestCounter++
serverApiElectrum.electrumRequestData(ctx, electrumRequest)
} else {
Toast.makeText(activity, getString(R.string.no_connection), Toast.LENGTH_SHORT).show()
srl?.isRefreshing = false
}
}
// private fun requestElectrum(electrumRequest: ElectrumRequest) {
// if (UtilHelper.isOnline(context as Activity)) {
// requestCounter++
// serverApiElectrum.electrumRequestData(ctx, electrumRequest)
// } else {
// Toast.makeText(activity, getString(R.string.no_connection), Toast.LENGTH_SHORT).show()
// srl?.isRefreshing = false
// }
// }
private fun requestInfura(method: String, contract: String) {
if (UtilHelper.isOnline(context as Activity)) {
requestCounter++
serverApiInfura.infura(method, 67, ctx.coinData!!.wallet, contract, "")
} else {
Toast.makeText(activity, getString(R.string.no_connection), Toast.LENGTH_SHORT).show()
srl?.isRefreshing = false
}
}
// private fun requestInfura(method: String, contract: String) {
// if (UtilHelper.isOnline(context as Activity)) {
// requestCounter++
// serverApiInfura.infura(method, 67, ctx.coinData!!.wallet, contract, "")
// } else {
// Toast.makeText(activity, getString(R.string.no_connection), Toast.LENGTH_SHORT).show()
// srl?.isRefreshing = false
// }
// }
private fun requestVerifyAndGetInfo() {
if (UtilHelper.isOnline(context as Activity)) {
if ((ctx.card!!.isOnlineVerified == null || !ctx.card!!.isOnlineVerified)) {
Log.i(TAG, "requestVerifyAndGetInfo")
requestCounter++
serverApiTangem.cardVerifyAndGetInfo(ctx.card)
}
} else {
Toast.makeText(activity, getString(R.string.no_connection), Toast.LENGTH_SHORT).show()
Log.e(TAG, "+++++++++++ Hide refresh 1")
srl?.isRefreshing = false
}
}
private fun requestRateInfo(cryptoId: String) {
if (UtilHelper.isOnline(context as Activity)) {
Log.i(TAG, "requestRateInfo")
serverApiCommon.rateInfoData(cryptoId)
} else {
Toast.makeText(activity, getString(R.string.no_connection), Toast.LENGTH_SHORT).show()
Log.e(TAG, "+++++++++++ Hide refresh 2")
srl?.isRefreshing = false
}
}
@ -894,7 +930,7 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
val sUID = Util.byteArrayToHexString(uid)
if (ctx.card.uid != sUID) {
// Log.d(TAG, "Invalid UID: $sUID")
nfcManager!!.ignoreTag(isoDep.tag)
nfcManager.ignoreTag(isoDep.tag)
return
} else {
// Log.v(TAG, "UID: $sUID")

View file

@ -39,7 +39,6 @@ class VerifyCard : Fragment(), NfcAdapter.ReaderCallback {
companion object {
val TAG: String = VerifyCard::class.java.simpleName
}
private var nfcManager: NfcManager? = null