Updated on 2026-08-14
This commit is contained in:
commit
8ba700a436
11 changed files with 667 additions and 362 deletions
|
|
@ -12,7 +12,8 @@ public enum Blockchain {
|
|||
Ethereum("ETH", "ETH", 1.0, R.drawable.ic_logo_ethereum, "Ethereum"),
|
||||
EthereumTestNet("ETH/test", "ETH", 1.0, R.drawable.ic_logo_ethereum_testnet, "Ethereum Testnet"),
|
||||
Token("Token", "ERC20", 1.0, R.drawable.ic_logo_bat_token, "Ethereum"),
|
||||
BitcoinCash("BCH", "BCH", 100000000.0, R.drawable.ic_logo_bitcoin_cash, "Bitcoin Cash");
|
||||
BitcoinCash("BCH", "BCH", 100000000.0, R.drawable.ic_logo_bitcoin_cash, "Bitcoin Cash"),
|
||||
Litecoin("LTC", "LTC", 100000000.0, R.drawable.ic_logo_bitcoin, "Litecoin");
|
||||
|
||||
Blockchain(String ID, String currency, double multiplier, int imageResource, String officialName) {
|
||||
mID = ID;
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import com.tangem.data.Blockchain;
|
|||
import com.tangem.domain.wallet.bch.BitcoinCashNode;
|
||||
import com.tangem.domain.wallet.btc.BitcoinNode;
|
||||
import com.tangem.domain.wallet.btc.BitcoinNodeTestNet;
|
||||
import com.tangem.domain.wallet.ltc.LitecoinNode;
|
||||
import com.tangem.wallet.R;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
|
|
@ -170,6 +171,7 @@ public class ServerApiElectrum {
|
|||
String host;
|
||||
int port;
|
||||
String proto;
|
||||
// todo - get available URL list from coinEngine, remove if( ctx.getBlockchain()==...)
|
||||
if (ctx.getBlockchain() == Blockchain.BitcoinTestNet) {
|
||||
BitcoinNodeTestNet bitcoinNodeTestNet = BitcoinNodeTestNet.values()[new Random().nextInt(BitcoinNodeTestNet.values().length)];
|
||||
host = bitcoinNodeTestNet.getHost();
|
||||
|
|
@ -203,6 +205,20 @@ public class ServerApiElectrum {
|
|||
this.host = host;
|
||||
this.port = port;
|
||||
|
||||
if (proto.equals("tcp")) {
|
||||
doElectrumRequestTcp(electrumRequest, host, port);
|
||||
} else {
|
||||
doElectrumRequestSsl(electrumRequest, host, port);
|
||||
}
|
||||
} else if (ctx.getBlockchain() == Blockchain.Litecoin) {
|
||||
LitecoinNode litecoinNode = LitecoinNode.values()[new Random().nextInt(LitecoinNode.values().length)];
|
||||
host = litecoinNode.getHost();
|
||||
port = litecoinNode.getPort();
|
||||
proto = litecoinNode.getProto();
|
||||
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
|
||||
if (proto.equals("tcp")) {
|
||||
doElectrumRequestTcp(electrumRequest, host, port);
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import com.tangem.domain.wallet.eth.EthEngine
|
|||
import com.tangem.domain.wallet.token.TokenEngine
|
||||
import com.tangem.domain.wallet.bch.BtcCashEngine
|
||||
import com.tangem.data.Blockchain
|
||||
import com.tangem.domain.wallet.ltc.LtcEngine
|
||||
|
||||
/**
|
||||
* Factory for create specific engine
|
||||
|
|
@ -25,6 +26,7 @@ object CoinEngineFactory {
|
|||
Blockchain.BitcoinCash -> BtcCashEngine()
|
||||
Blockchain.Ethereum, Blockchain.EthereumTestNet -> EthEngine()
|
||||
Blockchain.Token -> TokenEngine()
|
||||
Blockchain.Litecoin -> LtcEngine()
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
|
@ -40,6 +42,8 @@ object CoinEngineFactory {
|
|||
EthEngine(context)
|
||||
else if (Blockchain.Token == context.blockchain)
|
||||
TokenEngine(context)
|
||||
else if (Blockchain.Litecoin == context.blockchain)
|
||||
LtcEngine(context)
|
||||
else
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
|
|
|
|||
|
|
@ -566,11 +566,11 @@ public final class Transaction {
|
|||
public static Script buildOutput(String address) throws BitcoinException {
|
||||
//noinspection TryWithIdenticalCatches
|
||||
byte[] addressWithCheckSumAndNetworkCode = Base58.decodeBase58(address);
|
||||
if (addressWithCheckSumAndNetworkCode[0] == 0 || addressWithCheckSumAndNetworkCode[0] == 111) {
|
||||
if (addressWithCheckSumAndNetworkCode[0] == 0 || addressWithCheckSumAndNetworkCode[0] == 111 || addressWithCheckSumAndNetworkCode[0] == 48) { //0 for BTC/BCH 1 address | 48 for LTC L address
|
||||
return buildOutputP2H(address);
|
||||
}
|
||||
|
||||
if(addressWithCheckSumAndNetworkCode[0] == 5 || addressWithCheckSumAndNetworkCode[0] == (byte)0xc4) {
|
||||
if(addressWithCheckSumAndNetworkCode[0] == 5 || addressWithCheckSumAndNetworkCode[0] == (byte)0xc4 || addressWithCheckSumAndNetworkCode[0] == 50) { //5 for BTC/BCH/LTC 3 address | 50 for LTC M address
|
||||
return buildOutputP2SH(address);
|
||||
}
|
||||
|
||||
|
|
@ -579,7 +579,7 @@ public final class Transaction {
|
|||
public static Script buildOutputP2SH(String address) throws BitcoinException {
|
||||
try {
|
||||
byte[] addressWithCheckSumAndNetworkCode = Base58.decodeBase58(address);
|
||||
if (addressWithCheckSumAndNetworkCode[0] != 5 && addressWithCheckSumAndNetworkCode[0] != (byte)0xc4) {
|
||||
if (addressWithCheckSumAndNetworkCode[0] != 5 && addressWithCheckSumAndNetworkCode[0] != (byte)0xc4 && addressWithCheckSumAndNetworkCode[0] != 50) {
|
||||
throw new BitcoinException(BitcoinException.ERR_UNSUPPORTED, "Unknown address type", address);
|
||||
}
|
||||
|
||||
|
|
@ -601,7 +601,7 @@ public final class Transaction {
|
|||
//noinspection TryWithIdenticalCatches
|
||||
try {
|
||||
byte[] addressWithCheckSumAndNetworkCode = Base58.decodeBase58(address);
|
||||
if (addressWithCheckSumAndNetworkCode[0] != 0 && addressWithCheckSumAndNetworkCode[0] != 111) {
|
||||
if (addressWithCheckSumAndNetworkCode[0] != 0 && addressWithCheckSumAndNetworkCode[0] != 111 && addressWithCheckSumAndNetworkCode[0] != 48) {
|
||||
throw new BitcoinException(BitcoinException.ERR_UNSUPPORTED, "Unknown address type", address);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -179,9 +179,7 @@ public class BtcCashEngine extends CoinEngine {
|
|||
//
|
||||
// return true;
|
||||
|
||||
if (CashAddr.isValidCashAddress(address))
|
||||
return true;
|
||||
return false;
|
||||
return CashAddr.isValidCashAddress(address);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -191,7 +189,7 @@ public class BtcCashEngine extends CoinEngine {
|
|||
|
||||
@Override
|
||||
public Uri getShareWalletUriExplorer() {
|
||||
return Uri.parse((ctx.getBlockchain() == Blockchain.BitcoinCash ? "https://bitcoincash.blockexplorer.com/address/" : "https://testnet.blockexplorer.com/address/") + ctx.getCoinData().getWallet());
|
||||
return Uri.parse("https://bch.btc.com/" + ctx.getCoinData().getWallet());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -334,10 +332,10 @@ public class BtcCashEngine extends CoinEngine {
|
|||
}
|
||||
|
||||
@Override
|
||||
public String calculateAddress(byte[] pkUncompressed) throws NoSuchProviderException, NoSuchAlgorithmException {
|
||||
public String calculateAddress(byte[] pubKey) throws NoSuchProviderException, NoSuchAlgorithmException {
|
||||
|
||||
// CashAddr format
|
||||
byte hash1[] = Util.calculateSHA256(pkUncompressed);
|
||||
byte hash1[] = Util.calculateSHA256(pubKey);
|
||||
byte hash2[] = Util.calculateRIPEMD160(hash1);
|
||||
return CashAddr.toCashAddress(BitcoinCashAddressType.P2PKH, hash2);
|
||||
|
||||
|
|
@ -438,22 +436,25 @@ public class BtcCashEngine extends CoinEngine {
|
|||
return coinData.getUnspentInputsDescription();
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public String getAmountDescription(TangemCard mCard, String amount) throws Exception {
|
||||
// return mCard.getAmountDescription(Double.parseDouble(amount));
|
||||
// }
|
||||
|
||||
@Override
|
||||
public void defineWallet() throws CardProtocol.TangemException {
|
||||
try {
|
||||
String wallet = calculateAddress(ctx.getCard().getWalletPublicKeyRar());
|
||||
ctx.getCoinData().setWallet(wallet);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ctx.getCoinData().setWallet("ERROR");
|
||||
throw new CardProtocol.TangemException("Can't define wallet address");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public String getAmountDescription(TangemCard mCard, String amount) throws Exception {
|
||||
// return mCard.getAmountDescription(Double.parseDouble(amount));
|
||||
// }
|
||||
|
||||
|
||||
@Override
|
||||
public SignTask.PaymentToSign constructPayment(Amount amountValue, Amount feeValue, boolean IncFee, String targetAddress) throws Exception {
|
||||
|
|
@ -568,11 +569,6 @@ public class BtcCashEngine extends CoinEngine {
|
|||
public void onSuccess(ElectrumRequest electrumRequest) {
|
||||
if (electrumRequest.isMethod(ElectrumRequest.METHOD_GetBalance)) {
|
||||
try {
|
||||
String walletAddress = electrumRequest.getParams().getString(0);
|
||||
if (!walletAddress.equals(coinData.getWallet())) {
|
||||
// todo - check
|
||||
throw new Exception("Invalid wallet address in answer!");
|
||||
}
|
||||
Long confBalance = electrumRequest.getResult().getLong("confirmed");
|
||||
Long unconfirmedBalance = electrumRequest.getResult().getLong("unconfirmed");
|
||||
coinData.setBalanceReceived(true);
|
||||
|
|
@ -662,140 +658,86 @@ public class BtcCashEngine extends CoinEngine {
|
|||
serverApiElectrum.electrumRequestData(ctx, ElectrumRequest.listUnspent(convertToLegacyAddress(coinData.getWallet())));
|
||||
}
|
||||
|
||||
private Integer buildSize(String outputAddress, String outFee, String outAmount) {
|
||||
//todo - проверить, правильней было бы использовать constructPayment
|
||||
private Integer calculateEstimatedTransactionSize(String outputAddress, String outAmount) {
|
||||
try {
|
||||
String myAddress = coinData.getWallet();
|
||||
byte[] pbKey = ctx.getCard().getWalletPublicKey();
|
||||
byte[] pbComprKey = ctx.getCard().getWalletPublicKeyRar();
|
||||
SignTask.PaymentToSign ps=constructPayment(new Amount(outAmount, getBalanceCurrency()),new Amount("0.00",getFeeCurrency()), true, outputAddress );
|
||||
OnNeedSendPayment onNeedSendPaymentBackup=onNeedSendPayment;
|
||||
onNeedSendPayment=(tx)->{}; // empty function to bypass exception
|
||||
|
||||
// build script for our address
|
||||
List<BtcData.UnspentTransaction> rawTxList = coinData.getUnspentTransactions();
|
||||
byte[] outputScriptWeAreAbleToSpend = Transaction.Script.buildOutput(myAddress).bytes;
|
||||
|
||||
// collect unspent
|
||||
ArrayList<UnspentOutputInfo> unspentOutputs = BTCUtils.getOutputs(rawTxList, outputScriptWeAreAbleToSpend);
|
||||
|
||||
Long fullAmount = 0L;
|
||||
for (int i = 0; i < unspentOutputs.size(); i++) {
|
||||
fullAmount += unspentOutputs.get(i).value;
|
||||
}
|
||||
|
||||
// get first unspent
|
||||
// val outPut = unspentOutputs[0]
|
||||
// val outPutIndex = outPut.outputIndex
|
||||
|
||||
// get prev TX id;
|
||||
// val prevTXID = rawTxList[0].txID//"f67b838d6e2c0c587f476f583843e93ff20368eaf96a798bdc25e01f53f8f5d2";
|
||||
|
||||
Long fees = FormatUtil.ConvertStringToLong(outFee);
|
||||
Long amount = FormatUtil.ConvertStringToLong(outAmount);
|
||||
amount -= fees;
|
||||
|
||||
Long change = fullAmount - fees - amount;
|
||||
|
||||
if (amount + fees > fullAmount) {
|
||||
throw new Exception(String.format("Balance (%d) < amount (%d) + (%d)", fullAmount, change, amount));
|
||||
}
|
||||
|
||||
byte[][] hashesForSign = new byte[unspentOutputs.size()][];
|
||||
|
||||
for (int i = 0; i < unspentOutputs.size(); i++) {
|
||||
byte[] newTX = BTCUtils.buildTXForSign(myAddress, outputAddress, myAddress, unspentOutputs, i, amount, change);
|
||||
byte[] hashData = Util.calculateSHA256(newTX);
|
||||
byte[] 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;
|
||||
}
|
||||
|
||||
byte[] signFromCard = new byte[64 * unspentOutputs.size()];
|
||||
|
||||
for (int i = 0; i < unspentOutputs.size(); i++) {
|
||||
BigInteger r = new BigInteger(1, Arrays.copyOfRange(signFromCard, 0 + i * 64, 32 + i * 64));
|
||||
BigInteger s = new BigInteger(1, Arrays.copyOfRange(signFromCard, 32 + i * 64, 64 + i * 64));
|
||||
byte[] encodingSign = DerEncodingUtil.packSignDer(r, s, pbKey);
|
||||
unspentOutputs.get(i).scriptForBuild = encodingSign;
|
||||
}
|
||||
|
||||
byte[] realTX = BTCUtils.buildTXForSend(outputAddress, myAddress, unspentOutputs, amount, change);
|
||||
|
||||
return realTX.length;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
byte[][] hashesToSign=ps.getHashesToSign();
|
||||
byte[] signFromCard = new byte[64 * hashesToSign.length];
|
||||
byte[] txForSend=ps.onSignCompleted(signFromCard);
|
||||
onNeedSendPayment=onNeedSendPaymentBackup;
|
||||
Log.e(TAG,"txForSend.length="+String.valueOf(txForSend.length));
|
||||
return txForSend.length;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
Log.e(TAG, "Can't calculate transaction size -> use default!");
|
||||
return 256;
|
||||
}
|
||||
}
|
||||
|
||||
private final static BigDecimal relayFee = new BigDecimal(0.00001);
|
||||
|
||||
@Override
|
||||
public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) throws Exception {
|
||||
final int calcSize = buildSize(targetAddress, "0.00", amount.toValueString());
|
||||
final int calcSize = calculateEstimatedTransactionSize(targetAddress, amount.toValueString());
|
||||
Log.e(TAG, String.format("Estimated tx size %d", calcSize));
|
||||
coinData.minFee=null;
|
||||
coinData.maxFee=null;
|
||||
coinData.normalFee=null;
|
||||
|
||||
final ServerApiCommon serverApiCommon = new ServerApiCommon();
|
||||
final ServerApiElectrum serverApiElectrum = new ServerApiElectrum();
|
||||
|
||||
final ServerApiCommon.EstimateFeeListener estimateFeeListener = new ServerApiCommon.EstimateFeeListener() {
|
||||
final ServerApiElectrum.ElectrumRequestDataListener electrumListener = new ServerApiElectrum.ElectrumRequestDataListener () {
|
||||
@Override
|
||||
public void onSuccess(int blockCount, String estimateFeeResponse) {
|
||||
BigDecimal fee = new BigDecimal(estimateFeeResponse); // BTC per 1 kb
|
||||
public void onSuccess(ElectrumRequest electrumRequest) {
|
||||
BigDecimal fee;
|
||||
if (electrumRequest.isMethod(ElectrumRequest.METHOD_GetFee)) {
|
||||
try {
|
||||
fee = new BigDecimal(electrumRequest.getResultString()); //fee per KB
|
||||
|
||||
if (fee.equals(BigDecimal.ZERO)) {
|
||||
if (blockchainRequestsCallbacks.allowAdvance()) {
|
||||
serverApiCommon.estimateFee(blockCount);
|
||||
if (fee.equals(BigDecimal.ZERO)) {
|
||||
serverApiElectrum.electrumRequestData(ctx, ElectrumRequest.getFee());
|
||||
}
|
||||
|
||||
// if (calcSize != 0) {
|
||||
fee = fee.multiply(new BigDecimal(calcSize)).divide(new BigDecimal(1024)); // (per KB -> per byte)*size
|
||||
// } else {
|
||||
// serverApiElectrum.electrumRequestData(ctx, ElectrumRequest.getFee());
|
||||
// }
|
||||
|
||||
//compare fee to usual relay fee
|
||||
if (fee.compareTo(relayFee) < 0) {
|
||||
fee = relayFee;
|
||||
}
|
||||
fee = fee.setScale(8, RoundingMode.DOWN);
|
||||
|
||||
CoinEngine.Amount feeAmount = new CoinEngine.Amount(fee, ctx.getBlockchain().getCurrency());
|
||||
coinData.minFee = feeAmount;
|
||||
coinData.normalFee = feeAmount;
|
||||
coinData.maxFee = feeAmount;
|
||||
// if (coinData.minFee != null && coinData.normalFee != null && coinData.maxFee != null) {
|
||||
blockchainRequestsCallbacks.onComplete(true);
|
||||
// } else {
|
||||
// blockchainRequestsCallbacks.onProgress();
|
||||
// }
|
||||
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (calcSize != 0) {
|
||||
fee = fee.multiply(new BigDecimal(calcSize)).divide(new BigDecimal(1024)); // per Kb -> per byte
|
||||
} else {
|
||||
if (blockchainRequestsCallbacks.allowAdvance()) {
|
||||
serverApiCommon.estimateFee(blockCount);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
fee = fee.setScale(8, RoundingMode.DOWN);
|
||||
|
||||
switch (blockCount) {
|
||||
case ServerApiCommon.ESTIMATE_FEE_MINIMAL:
|
||||
coinData.minFee = new CoinEngine.Amount(fee, getFeeCurrency());
|
||||
break;
|
||||
case ServerApiCommon.ESTIMATE_FEE_NORMAL:
|
||||
coinData.normalFee = new CoinEngine.Amount(fee, getFeeCurrency());
|
||||
break;
|
||||
case ServerApiCommon.ESTIMATE_FEE_PRIORITY:
|
||||
coinData.maxFee = new CoinEngine.Amount(fee, getFeeCurrency());
|
||||
break;
|
||||
}
|
||||
blockchainRequestsCallbacks.onComplete(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFail(int blockCount, String message) {
|
||||
// TODO - add fail counter to terminate after NNN tries
|
||||
if (blockchainRequestsCallbacks.allowAdvance()) {
|
||||
serverApiCommon.estimateFee(blockCount);
|
||||
}
|
||||
ctx.setError(ctx.getContext().getString(R.string.cannot_calculate_fee_wrong_data_received_from_node));
|
||||
public void onFail(ElectrumRequest electrumRequest) {
|
||||
ctx.setError(electrumRequest.getError());
|
||||
blockchainRequestsCallbacks.onComplete(false);
|
||||
}
|
||||
};
|
||||
serverApiCommon.setEstimateFee(estimateFeeListener);
|
||||
|
||||
serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_PRIORITY);
|
||||
serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_NORMAL);
|
||||
serverApiCommon.estimateFee(ServerApiCommon.ESTIMATE_FEE_MINIMAL);
|
||||
serverApiElectrum.setElectrumRequestData(electrumListener);
|
||||
|
||||
serverApiElectrum.electrumRequestData(ctx, ElectrumRequest.getFee());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -623,7 +623,7 @@ public class BtcEngine extends CoinEngine {
|
|||
serverApiElectrum.electrumRequestData(ctx, ElectrumRequest.listUnspent(coinData.getWallet()));
|
||||
}
|
||||
|
||||
private Integer calculateEstimatedTransactionSize(String outputAddress, String outAmount) {
|
||||
protected Integer calculateEstimatedTransactionSize(String outputAddress, String outAmount) {
|
||||
//todo - правильней было бы использовать constructPayment
|
||||
try {
|
||||
// String myAddress = coinData.getWallet();
|
||||
|
|
@ -708,7 +708,7 @@ public class BtcEngine extends CoinEngine {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) {
|
||||
public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) throws Exception {
|
||||
final int calcSize = calculateEstimatedTransactionSize(targetAddress, amount.toValueString());
|
||||
Log.e(TAG, String.format("Estimated tx size %d", calcSize));
|
||||
coinData.minFee = null;
|
||||
|
|
|
|||
560
app/src/main/java/com/tangem/domain/wallet/ltc/LtcEngine.java
Normal file
560
app/src/main/java/com/tangem/domain/wallet/ltc/LtcEngine.java
Normal file
|
|
@ -0,0 +1,560 @@
|
|||
package com.tangem.domain.wallet.ltc;
|
||||
|
||||
import android.net.Uri;
|
||||
import android.text.InputFilter;
|
||||
import android.util.Log;
|
||||
|
||||
import com.tangem.data.network.ElectrumRequest;
|
||||
import com.tangem.data.network.ServerApiElectrum;
|
||||
import com.tangem.domain.wallet.BTCUtils;
|
||||
import com.tangem.domain.wallet.BalanceValidator;
|
||||
import com.tangem.domain.wallet.Base58;
|
||||
import com.tangem.domain.wallet.CoinData;
|
||||
import com.tangem.domain.wallet.CoinEngine;
|
||||
import com.tangem.domain.wallet.TangemContext;
|
||||
import com.tangem.domain.wallet.Transaction;
|
||||
import com.tangem.domain.wallet.UnspentOutputInfo;
|
||||
import com.tangem.domain.wallet.btc.BtcData;
|
||||
import com.tangem.domain.wallet.btc.BtcEngine;
|
||||
import com.tangem.tangemcard.data.TangemCard;
|
||||
import com.tangem.tangemcard.reader.CardProtocol;
|
||||
import com.tangem.tangemcard.tasks.SignTask;
|
||||
import com.tangem.tangemcard.util.Util;
|
||||
import com.tangem.util.CryptoUtil;
|
||||
import com.tangem.util.DecimalDigitsInputFilter;
|
||||
import com.tangem.util.DerEncodingUtil;
|
||||
import com.tangem.wallet.R;
|
||||
|
||||
import org.json.JSONException;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class LtcEngine extends BtcEngine {
|
||||
private static final String TAG = LtcEngine.class.getSimpleName();
|
||||
public BtcData coinData = null;
|
||||
|
||||
public LtcEngine(TangemContext context) throws Exception {
|
||||
super(context);
|
||||
if (context.getCoinData() == null) {
|
||||
coinData = new BtcData();
|
||||
context.setCoinData(coinData);
|
||||
} else if (context.getCoinData() instanceof BtcData) {
|
||||
coinData = (BtcData) context.getCoinData();
|
||||
} else {
|
||||
throw new Exception("Invalid type of Blockchain data for LtcEngine");
|
||||
}
|
||||
}
|
||||
|
||||
public LtcEngine() {
|
||||
super();
|
||||
}
|
||||
|
||||
private static int getDecimals() {
|
||||
return 8;
|
||||
}
|
||||
|
||||
|
||||
private void checkBlockchainDataExists() throws Exception {
|
||||
if (coinData == null) throw new Exception("No blockchain data");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean awaitingConfirmation() {
|
||||
if (coinData == null) return false;
|
||||
return coinData.getBalanceUnconfirmed() != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBalanceHTML() {
|
||||
Amount balance = getBalance();
|
||||
if (balance != null) {
|
||||
return balance.toDescriptionString(getDecimals());
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBalanceCurrency() {
|
||||
return "LTC";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOfflineBalanceHTML() {
|
||||
InternalAmount offlineInternalAmount = convertToInternalAmount(ctx.getCard().getOfflineBalance());
|
||||
Amount offlineAmount = convertToAmount(offlineInternalAmount);
|
||||
return offlineAmount.toDescriptionString(getDecimals());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBalanceNotZero() {
|
||||
if (coinData == null) return false;
|
||||
if (coinData.getBalanceInInternalUnits() == null) return false;
|
||||
return coinData.getBalanceInInternalUnits().notZero();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasBalanceInfo() {
|
||||
if (coinData == null) return false;
|
||||
return coinData.hasBalanceInfo();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isExtractPossible() {
|
||||
if (!hasBalanceInfo()) {
|
||||
ctx.setMessage(R.string.cannot_obtain_data_from_blockchain);
|
||||
} else if (!isBalanceNotZero()) {
|
||||
ctx.setMessage(R.string.wallet_empty);
|
||||
} else if (awaitingConfirmation()) {
|
||||
ctx.setMessage(R.string.please_wait_while_previous);
|
||||
} else if (coinData.getUnspentTransactions().size() == 0) {
|
||||
ctx.setMessage(R.string.please_wait_for_confirmation);
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFeeCurrency() {
|
||||
return "LTC";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateAddress(String address) {
|
||||
if (address == null || address.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (address.length() < 25) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (address.length() > 35) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!address.startsWith("L") && !address.startsWith("M")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] decAddress = Base58.decodeBase58(address);
|
||||
|
||||
if (decAddress == null || decAddress.length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] rip = new byte[21];
|
||||
for (int i = 0; i < 21; ++i) {
|
||||
rip[i] = decAddress[i];
|
||||
}
|
||||
|
||||
byte[] kcv = CryptoUtil.doubleSha256(rip);
|
||||
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
if (kcv[i] != decAddress[21 + i])
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isNeedCheckNode() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Uri getShareWalletUriExplorer() {
|
||||
return Uri.parse("https://live.blockcypher.com/ltc/address/" + ctx.getCoinData().getWallet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Uri getShareWalletUri() {
|
||||
if (ctx.getCard().getDenomination() != null) {
|
||||
return Uri.parse("litecoin:" + ctx.getCoinData().getWallet() + "?amount=" + convertToAmount(convertToInternalAmount(ctx.getCard().getDenomination())).toValueString(8));
|
||||
} else {
|
||||
return Uri.parse("litecoin:" + ctx.getCoinData().getWallet());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputFilter[] getAmountInputFilters() {
|
||||
return new InputFilter[]{new DecimalDigitsInputFilter(getDecimals())};
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkNewTransactionAmount(Amount amount) {
|
||||
if (coinData == null) return false;
|
||||
if (amount.compareTo(convertToAmount(coinData.getBalanceInInternalUnits())) > 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkNewTransactionAmountAndFee(Amount amountValue, Amount feeValue, Boolean isIncludeFee) {
|
||||
InternalAmount fee;
|
||||
InternalAmount amount;
|
||||
|
||||
try {
|
||||
checkBlockchainDataExists();
|
||||
amount = convertToInternalAmount(amountValue);
|
||||
fee = convertToInternalAmount(feeValue);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fee == null || amount == null)
|
||||
return false;
|
||||
|
||||
if (fee.isZero() || amount.isZero())
|
||||
return false;
|
||||
|
||||
if (isIncludeFee && (amount.compareTo(coinData.getBalanceInInternalUnits()) > 0 || amount.compareTo(fee) < 0))
|
||||
return false;
|
||||
|
||||
if (!isIncludeFee && amount.add(fee).compareTo(coinData.getBalanceInInternalUnits()) > 0)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateBalance(BalanceValidator balanceValidator) {
|
||||
if (((ctx.getCard().getOfflineBalance() == null) && !ctx.getCoinData().isBalanceReceived()) || (!ctx.getCoinData().isBalanceReceived() && (ctx.getCard().getRemainingSignatures() != ctx.getCard().getMaxSignatures()))) {
|
||||
balanceValidator.setScore(0);
|
||||
balanceValidator.setFirstLine("Unknown balance");
|
||||
balanceValidator.setSecondLine("Balance cannot be verified. Swipe down to refresh.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Workaround before new back-end
|
||||
// if (card.getRemainingSignatures() == card.getMaxSignatures()) {
|
||||
// firstLine = "Verified balance";
|
||||
// secondLine = "Balance confirmed in blockchain. ";
|
||||
// secondLine += "Verified note identity. ";
|
||||
// return;
|
||||
// }
|
||||
|
||||
if (coinData.getBalanceUnconfirmed() != 0) {
|
||||
balanceValidator.setScore(0);
|
||||
balanceValidator.setFirstLine("Transaction in progress");
|
||||
balanceValidator.setSecondLine("Wait for confirmation in blockchain");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (coinData.isBalanceReceived() && coinData.isBalanceEqual()) {
|
||||
balanceValidator.setScore(100);
|
||||
balanceValidator.setFirstLine("Verified balance");
|
||||
balanceValidator.setSecondLine("Balance confirmed in blockchain");
|
||||
if (coinData.getBalanceInInternalUnits().isZero()) {
|
||||
balanceValidator.setFirstLine("Empty wallet");
|
||||
balanceValidator.setSecondLine("");
|
||||
}
|
||||
}
|
||||
|
||||
// rule 4 TODO: need to check SignedHashed against number of outputs in blockchain
|
||||
// if((card.getRemainingSignatures() != card.getMaxSignatures()) && card.getBalance() != 0)
|
||||
// {
|
||||
// score = 80;
|
||||
// firstLine = "Unguaranteed balance";
|
||||
// secondLine = "Potential unsent transaction. Redeem immediately if accept. ";
|
||||
// return;
|
||||
// }
|
||||
|
||||
if ((ctx.getCard().getOfflineBalance() != null) && !coinData.isBalanceReceived() && (ctx.getCard().getRemainingSignatures() == ctx.getCard().getMaxSignatures()) && coinData.getBalanceInInternalUnits().notZero()) {
|
||||
balanceValidator.setScore(80);
|
||||
balanceValidator.setFirstLine("Verified offline balance");
|
||||
balanceValidator.setSecondLine("Can't obtain balance from blockchain. Restore internet connection to be more confident. ");
|
||||
}
|
||||
|
||||
// if(card.getFailedBalanceRequestCounter()!=0) {
|
||||
// score -= 5 * card.getFailedBalanceRequestCounter();
|
||||
// secondLine += "Not all nodes have returned balance. Swipe down or tap again. ";
|
||||
// if(score <= 0)
|
||||
// return;
|
||||
// }
|
||||
|
||||
//
|
||||
// if(card.isBalanceReceived() && !card.isBalanceEqual()) {
|
||||
// score = 0;
|
||||
// firstLine = "Disputed balance";
|
||||
// secondLine += " Cannot obtain trusted balance at the moment. Try to tap and check this banknote later.";
|
||||
// return;
|
||||
// }
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Amount getBalance() {
|
||||
if (!hasBalanceInfo()) return null;
|
||||
return convertToAmount(coinData.getBalanceInInternalUnits());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String evaluateFeeEquivalent(String fee) {
|
||||
if (!coinData.getAmountEquivalentDescriptionAvailable()) return "";
|
||||
try {
|
||||
Amount feeAmount = new Amount(fee, getFeeCurrency());
|
||||
return feeAmount.toEquivalentString(coinData.getRate());
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBalanceEquivalent() {
|
||||
if (coinData == null || !coinData.getAmountEquivalentDescriptionAvailable()) return "";
|
||||
Amount balance = getBalance();
|
||||
if (balance == null) return "";
|
||||
return balance.toEquivalentString(coinData.getRate());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String calculateAddress(byte[] pkUncompressed) throws NoSuchProviderException, NoSuchAlgorithmException {
|
||||
byte netSelectionByte = (byte) 0x30;
|
||||
|
||||
byte hash1[] = Util.calculateSHA256(pkUncompressed);
|
||||
byte hash2[] = Util.calculateRIPEMD160(hash1);
|
||||
|
||||
ByteBuffer BB = ByteBuffer.allocate(hash2.length + 1);
|
||||
|
||||
BB.put(netSelectionByte);
|
||||
BB.put(hash2);
|
||||
|
||||
byte hash3[] = Util.calculateSHA256(BB.array());
|
||||
byte hash4[] = Util.calculateSHA256(hash3);
|
||||
|
||||
BB = ByteBuffer.allocate(hash2.length + 5);
|
||||
BB.put(netSelectionByte); //BB.put((byte) 0x6f);
|
||||
BB.put(hash2);
|
||||
BB.put(hash4[0]);
|
||||
BB.put(hash4[1]);
|
||||
BB.put(hash4[2]);
|
||||
BB.put(hash4[3]);
|
||||
|
||||
return org.bitcoinj.core.Base58.encode(BB.array());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Amount convertToAmount(InternalAmount internalAmount) {
|
||||
BigDecimal d = internalAmount.divide(new BigDecimal("100000000"));
|
||||
return new Amount(d, getBalanceCurrency());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Amount convertToAmount(String strAmount, String currency) {
|
||||
return new Amount(strAmount, currency);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InternalAmount convertToInternalAmount(Amount amount) {
|
||||
BigDecimal d = amount.multiply(new BigDecimal("100000000"));
|
||||
return new InternalAmount(d, "Satoshi");
|
||||
}
|
||||
|
||||
@Override
|
||||
public InternalAmount convertToInternalAmount(byte[] bytes) {
|
||||
if (bytes == null) return null;
|
||||
byte[] reversed = new byte[bytes.length];
|
||||
for (int i = 0; i < bytes.length; i++) reversed[i] = bytes[bytes.length - i - 1];
|
||||
return new InternalAmount(Util.byteArrayToLong(reversed), "Satoshi");
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] convertToByteArray(InternalAmount internalAmount) {
|
||||
byte[] bytes = Util.longToByteArray(internalAmount.longValueExact());
|
||||
byte[] reversed = new byte[bytes.length];
|
||||
for (int i = 0; i < bytes.length; i++) reversed[i] = bytes[bytes.length - i - 1];
|
||||
return reversed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CoinData createCoinData() {
|
||||
return new BtcData();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUnspentInputsDescription() {
|
||||
return coinData.getUnspentInputsDescription();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SignTask.PaymentToSign constructPayment(Amount amountValue, Amount feeValue, boolean IncFee, String targetAddress) throws Exception {
|
||||
final ArrayList<UnspentOutputInfo> unspentOutputs;
|
||||
checkBlockchainDataExists();
|
||||
|
||||
String myAddress = ctx.getCoinData().getWallet();
|
||||
byte[] pbKey = ctx.getCard().getWalletPublicKey();
|
||||
|
||||
// Build script for our address
|
||||
List<BtcData.UnspentTransaction> rawTxList = coinData.getUnspentTransactions();
|
||||
byte[] outputScriptWeAreAbleToSpend = Transaction.Script.buildOutput(myAddress).bytes;
|
||||
|
||||
// Collect unspent
|
||||
unspentOutputs = BTCUtils.getOutputs(rawTxList, outputScriptWeAreAbleToSpend);
|
||||
|
||||
long fullAmount = 0;
|
||||
for (int i = 0; i < unspentOutputs.size(); ++i) {
|
||||
fullAmount += unspentOutputs.get(i).value;
|
||||
}
|
||||
|
||||
long fees = convertToInternalAmount(feeValue).longValueExact();
|
||||
long amount = convertToInternalAmount(amountValue).longValueExact();
|
||||
long change = fullAmount - amount;
|
||||
if (IncFee) {
|
||||
amount = amount - fees;
|
||||
} else {
|
||||
change = change - fees;
|
||||
}
|
||||
|
||||
final long amountFinal=amount;
|
||||
final long changeFinal=change;
|
||||
|
||||
if (amount + fees > fullAmount) {
|
||||
throw new CardProtocol.TangemException_WrongAmount(String.format("Balance (%d) < change (%d) + amount (%d)", fullAmount, change, amount));
|
||||
}
|
||||
|
||||
final byte[][] txForSign = new byte[unspentOutputs.size()][];
|
||||
final byte[][] bodyDoubleHash = new byte[unspentOutputs.size()][];
|
||||
final byte[][] bodyHash= new byte[unspentOutputs.size()][];
|
||||
|
||||
for (int i = 0; i < unspentOutputs.size(); ++i) {
|
||||
txForSign[i] = BTCUtils.buildTXForSign(myAddress, targetAddress, myAddress, unspentOutputs, i, amount, change);
|
||||
bodyHash[i] = Util.calculateSHA256(txForSign[i]);
|
||||
bodyDoubleHash[i] = Util.calculateSHA256(bodyHash[i]);
|
||||
}
|
||||
|
||||
return new SignTask.PaymentToSign() {
|
||||
|
||||
@Override
|
||||
public boolean isSigningMethodSupported(TangemCard.SigningMethod signingMethod) {
|
||||
return signingMethod==TangemCard.SigningMethod.Sign_Hash || signingMethod==TangemCard.SigningMethod.Sign_Raw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[][] getHashesToSign() throws Exception {
|
||||
byte[][] dataForSign=new byte[unspentOutputs.size()][];
|
||||
if (txForSign.length > 10) throw new Exception("To much hashes in one transaction!");
|
||||
for (int i = 0; i < unspentOutputs.size(); ++i) {
|
||||
dataForSign[i] = bodyDoubleHash[i];
|
||||
}
|
||||
return dataForSign;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getRawDataToSign() throws Exception {
|
||||
ByteArrayOutputStream bs = new ByteArrayOutputStream();
|
||||
for (int i = 0; i < txForSign.length; i++) {
|
||||
if (i != 0 && txForSign[0].length != txForSign[i].length)
|
||||
throw new Exception("Hashes length must be identical!");
|
||||
bs.write(txForSign[i]);
|
||||
}
|
||||
|
||||
return bs.toByteArray();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHashAlgToSign() {
|
||||
return "sha-256x2";
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getIssuerTransactionSignature(byte[] dataToSignByIssuer) throws Exception {
|
||||
throw new Exception("Issuer validation not supported!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] onSignCompleted(byte[] signFromCard) throws Exception {
|
||||
for (int i = 0; i < unspentOutputs.size(); ++i) {
|
||||
BigInteger r = new BigInteger(1, Arrays.copyOfRange(signFromCard, i * 64, 32 + i * 64));
|
||||
BigInteger s = new BigInteger(1, Arrays.copyOfRange(signFromCard, 32 + i * 64, 64 + i * 64));
|
||||
s = CryptoUtil.toCanonicalised(s);
|
||||
|
||||
unspentOutputs.get(i).scriptForBuild = DerEncodingUtil.packSignDer(r, s, pbKey);
|
||||
}
|
||||
|
||||
byte[] txForSend=BTCUtils.buildTXForSend(targetAddress, myAddress, unspentOutputs, amountFinal, changeFinal);
|
||||
notifyOnNeedSendPayment(txForSend);
|
||||
return txForSend;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private final static BigDecimal relayFee = new BigDecimal(0.00001);
|
||||
|
||||
@Override
|
||||
public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) throws Exception {
|
||||
final int calcSize = calculateEstimatedTransactionSize(targetAddress, amount.toValueString());
|
||||
Log.e(TAG, String.format("Estimated tx size %d", calcSize));
|
||||
coinData.minFee=null;
|
||||
coinData.maxFee=null;
|
||||
coinData.normalFee=null;
|
||||
|
||||
final ServerApiElectrum serverApiElectrum = new ServerApiElectrum();
|
||||
|
||||
final ServerApiElectrum.ElectrumRequestDataListener electrumListener = new ServerApiElectrum.ElectrumRequestDataListener () {
|
||||
@Override
|
||||
public void onSuccess(ElectrumRequest electrumRequest) {
|
||||
BigDecimal fee;
|
||||
if (electrumRequest.isMethod(ElectrumRequest.METHOD_GetFee)) {
|
||||
try {
|
||||
fee = new BigDecimal(electrumRequest.getResultString()); //fee per KB
|
||||
|
||||
if (fee.equals(BigDecimal.ZERO)) {
|
||||
serverApiElectrum.electrumRequestData(ctx, ElectrumRequest.getFee());
|
||||
}
|
||||
|
||||
// if (calcSize != 0) {
|
||||
fee = fee.multiply(new BigDecimal(calcSize)).divide(new BigDecimal(1024)); // (per KB -> per byte)*size
|
||||
// } else {
|
||||
// serverApiElectrum.electrumRequestData(ctx, ElectrumRequest.getFee());
|
||||
// }
|
||||
|
||||
//compare fee to usual relay fee
|
||||
if (fee.compareTo(relayFee) < 0) {
|
||||
fee = relayFee;
|
||||
}
|
||||
fee = fee.setScale(8, RoundingMode.DOWN);
|
||||
|
||||
CoinEngine.Amount feeAmount = new CoinEngine.Amount(fee, ctx.getBlockchain().getCurrency());
|
||||
coinData.minFee = feeAmount;
|
||||
coinData.normalFee = feeAmount;
|
||||
coinData.maxFee = feeAmount;
|
||||
// if (coinData.minFee != null && coinData.normalFee != null && coinData.maxFee != null) {
|
||||
blockchainRequestsCallbacks.onComplete(true);
|
||||
// } else {
|
||||
// blockchainRequestsCallbacks.onProgress();
|
||||
// }
|
||||
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFail(ElectrumRequest electrumRequest) {
|
||||
ctx.setError(electrumRequest.getError());
|
||||
blockchainRequestsCallbacks.onComplete(false);
|
||||
}
|
||||
};
|
||||
serverApiElectrum.setElectrumRequestData(electrumListener);
|
||||
|
||||
serverApiElectrum.electrumRequestData(ctx, ElectrumRequest.getFee());
|
||||
}
|
||||
}
|
||||
|
|
@ -725,7 +725,7 @@ public class TokenEngine extends CoinEngine {
|
|||
String gasPrice = infuraResponse.getResult();
|
||||
gasPrice = gasPrice.substring(2);
|
||||
// rounding gas price to integer gwei
|
||||
BigInteger l = new BigInteger(gasPrice, 16).divide(BigInteger.valueOf(1000000000L)).multiply(BigInteger.valueOf(1000000000L));
|
||||
BigInteger l = new 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)
|
||||
BigInteger m;
|
||||
|
|
|
|||
|
|
@ -88,7 +88,8 @@ class ConfirmPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback {
|
|||
// feeRequestSuccess = false
|
||||
// balanceRequestSuccess = false
|
||||
|
||||
if (ctx.blockchain == Blockchain.Ethereum || ctx.blockchain == Blockchain.EthereumTestNet || ctx.blockchain == Blockchain.Token) {
|
||||
if (ctx.blockchain == Blockchain.Ethereum || ctx.blockchain == Blockchain.EthereumTestNet || ctx.blockchain == Blockchain.Token ||
|
||||
ctx.blockchain == Blockchain.BitcoinCash || ctx.blockchain == Blockchain.Litecoin) {
|
||||
rgFee.isEnabled = false
|
||||
|
||||
// requestInfura(ServerApiInfura.INFURA_ETH_GAS_PRICE)
|
||||
|
|
|
|||
|
|
@ -91,8 +91,6 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
|
|||
ctx = TangemContext.loadFromBundle(activity, activity?.intent?.extras)
|
||||
|
||||
lastTag = activity?.intent?.getParcelableExtra(Constant.EXTRA_LAST_DISCOVERED_TAG)
|
||||
|
||||
//localStorage = activity?.let { CardDataSubstitutionProvider(it) }!!
|
||||
}
|
||||
|
||||
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
|
||||
|
|
@ -200,201 +198,6 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
|
|||
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()
|
||||
////
|
||||
//// //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
|
||||
// }
|
||||
//
|
||||
// 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?) {
|
||||
|
|
@ -817,61 +620,39 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific
|
|||
)
|
||||
|
||||
|
||||
// TODO - move requestRateInfo to CoinEngine
|
||||
|
||||
// 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))
|
||||
requestRateInfo("bitcoin")
|
||||
}
|
||||
|
||||
// Litecoin
|
||||
if (ctx.blockchain == Blockchain.Litecoin) {
|
||||
ctx.coinData.setIsBalanceEqual(true)
|
||||
|
||||
requestRateInfo("litecoin")
|
||||
}
|
||||
|
||||
// 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)))
|
||||
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, "")
|
||||
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))
|
||||
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 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)) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue