Updated on 2026-08-14

This commit is contained in:
Tangem 2018-10-10 22:04:20 +03:00
parent d1dc50123f
commit 6c8c365317
16 changed files with 160 additions and 1355 deletions

View file

@ -0,0 +1,153 @@
package com.tangem.data.network;
import android.util.Log;
import com.tangem.data.network.request.ElectrumRequest;
import com.tangem.domain.BitcoinNode;
import com.tangem.domain.BitcoinNodeTestNet;
import com.tangem.domain.wallet.Blockchain;
import com.tangem.domain.wallet.TangemCard;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
public class ServerApiHelperElectrum {
private static String TAG = ServerApiHelper.class.getSimpleName();
/**
* TCP
* Used in BTC
*/
private String host;
private int port;
private ElectrumRequestDataListener electrumRequestDataListener;
public interface ElectrumRequestDataListener {
void onElectrumRequestData(ElectrumRequest electrumRequest);
}
public void setElectrumRequestData(ElectrumRequestDataListener listener) {
electrumRequestDataListener = listener;
}
public void electrumRequestData(TangemCard card, ElectrumRequest electrumRequest) {
Observable<ElectrumRequest> checkBalanceObserver = Observable.just(electrumRequest)
.doOnNext(electrumRequest1 -> doElectrumRequest(card, electrumRequest))
.flatMap(electrumRequest1 -> {
if (electrumRequest1.answerData == null)
return Observable.error(new NullPointerException());
else
return Observable.just(electrumRequest1);
})
.retryWhen(errors -> errors
.filter(throwable -> throwable instanceof NullPointerException)
.zipWith(Observable.range(1, 2), (n, i) -> i))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
checkBalanceObserver.subscribe(new DefaultObserver<ElectrumRequest>() {
@Override
public void onNext(ElectrumRequest v) {
if (electrumRequest.answerData != null) {
electrumRequestDataListener.onElectrumRequestData(electrumRequest);
Log.i(TAG, "electrumRequestData " + electrumRequest.getMethod() + " onNext != null");
} else {
Log.e(TAG, "electrumRequestData " + electrumRequest.getMethod() + " onNext == null");
}
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "electrumRequestData " + electrumRequest.getMethod() + " onError " + e.getMessage());
}
@Override
public void onComplete() {
Log.i(TAG, "electrumRequestData " + electrumRequest.getMethod() + " onComplete");
}
});
}
private List<ElectrumRequest> doElectrumRequest(TangemCard card, ElectrumRequest electrumRequest) {
BitcoinNode bitcoinNode = BitcoinNode.values()[new Random().nextInt(BitcoinNode.values().length)];
if (card.getBlockchain() == Blockchain.BitcoinTestNet || card.getBlockchain() == Blockchain.BitcoinCashTestNet) {
BitcoinNodeTestNet bitcoinNodeTestNet = BitcoinNodeTestNet.values()[new Random().nextInt(BitcoinNodeTestNet.values().length)];
this.host = bitcoinNodeTestNet.getHost();
this.port = bitcoinNodeTestNet.getPort();
} else {
this.host = bitcoinNode.getHost();
this.port = bitcoinNode.getPort();
}
List<ElectrumRequest> result = new ArrayList<>();
Collections.addAll(result, electrumRequest);
try {
// Log.i(TAG, "host " + host + " !!!!!!!!!!!! " + "port " + String.valueOf(port));
InetAddress serverAddress = InetAddress.getByName(host);
Socket socket = new Socket();
socket.setSoTimeout(5000);
socket.bind(new InetSocketAddress(0));
socket.connect(new InetSocketAddress(serverAddress, port));
try {
// Log.i(TAG, "<< ");
OutputStream os = socket.getOutputStream();
OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
InputStream is = socket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
electrumRequest.setID(1);
// do request
try {
out.write(electrumRequest.getAsString() + "\n");
out.flush();
electrumRequest.answerData = in.readLine();
electrumRequest.host = host;
electrumRequest.port = port;
if (electrumRequest.answerData != null) {
// Log.i(TAG, ">> " + electrumRequest.answerData);
} else {
electrumRequest.error = "No answer from server";
// Log.i(TAG, ">> <NULL>");
}
} catch (Exception e) {
electrumRequest.error = e.toString();
}
} catch (Exception e) {
e.printStackTrace();
// Log.i(TAG, e.getMessage());
} finally {
// Log.i(TAG, "close");
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public String getValidationNodeDescription() {
return "Electrum, " + host + ":" + String.valueOf(port);
}
}

View file

@ -1,9 +1,9 @@
package com.tangem.data.network;
public class ServerURL {
public static final String API_TANGEM = "https://verify.tangem.com/";
public static final String API_COINMARKETCAP = "https://api.coinmarketcap.com/";
public static final String API_INFURA = "https://mainnet.infura.io/";
public static final String API_ESTIMATEFEE = " https://estimatefee.com/";
public static final String API_UPDATE_VERSION = "https://raw.githubusercontent.com/";
class ServerURL {
static final String API_TANGEM = "https://verify.tangem.com/";
static final String API_COINMARKETCAP = "https://api.coinmarketcap.com/";
static final String API_INFURA = "https://mainnet.infura.io/";
static final String API_ESTIMATEFEE = " https://estimatefee.com/";
static final String API_UPDATE_VERSION = "https://raw.githubusercontent.com/";
}

View file

@ -1,127 +0,0 @@
package com.tangem.data.network.task;
import android.os.AsyncTask;
import android.util.Log;
import com.tangem.data.network.request.ElectrumRequest;
import com.tangem.domain.wallet.SharedData;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by dvol on 16.07.2017.
*/
public class ElectrumTask extends AsyncTask<ElectrumRequest, Integer, List<ElectrumRequest>> {
public static final String logTag = "Electrum";
//public static final String host = /*"hsmiths.changeip.net";*/ "testnetnode.arihanc.com";
//public static final int port = /*8080*/51001;
private int reqID = 1;
private String Host = "";
private int Port = 0;
OutputStreamWriter out;
BufferedReader in;
public SharedData sharedCounter = null;
public ElectrumTask(String host, int port) {
super();
Host = host;
Port = port;
}
public ElectrumTask(String host, int port, SharedData sharedCounter) {
super();
Host = host;
Port = port;
this.sharedCounter = sharedCounter;
}
@Override
protected List<ElectrumRequest> doInBackground(ElectrumRequest... requests) {
List<ElectrumRequest> result = new ArrayList<>();
// for (int i = 0; i < requests.length; i++) {
// result.add(requests[i]);
// }
Collections.addAll(result, requests);
try {
InetAddress serverAddress = InetAddress.getByName(Host);
Log.v(logTag, "Connecting..." + Host);
// Socket socket = new Socket(serverAddress, port);
Socket socket = new Socket();
// socket.setSoTimeout(5000);
socket.setSoTimeout(10000);
socket.bind(new InetSocketAddress(0));
socket.connect(new InetSocketAddress(serverAddress, Port));
// Log.i("effefefe", host);
// Log.i("effefefe", String.valueOf(port));
try {
OutputStream os = socket.getOutputStream();
out = new OutputStreamWriter(os, "UTF-8");
Log.v(logTag, "Connected");
InputStream is = socket.getInputStream();
in = new BufferedReader(new InputStreamReader(is));
publishProgress(5);
for (int i = 0; i < requests.length; i++) {
requests[i].setID(reqID++);
doRequest(requests[i]);
publishProgress(5 + 90 * (i + 1) / requests.length);
}
publishProgress(100);
} catch (Exception e) {
Log.e(logTag, "Error: ", e);
} finally {
socket.close();
}
} catch (Exception e) {
Log.e(logTag, "Error: ", e);
for (int i = 0; i < requests.length; i++) {
result.get(i).error = e.toString();
}
}
return result;
}
private void doRequest(ElectrumRequest request) {
try {
Log.v(logTag, "<< " + request.getAsString());
out.write(request.getAsString() + "\n");
out.flush();
request.answerData = in.readLine();
request.host = Host;
request.port = Port;
if (request.answerData != null) {
Log.v(logTag, ">> " + request.answerData);
} else {
request.error = "No answer from server";
Log.v(logTag, ">> <NULL>");
}
} catch (Exception e) {
request.error = e.toString();
}
}
public String getValidationNodeDescription() {
return "Electrum, " + Host + ":" + String.valueOf(Port);
}
}

View file

@ -1,66 +0,0 @@
package com.tangem.data.network.task;
/**
* Created by Ilia on 16.01.2018.
*/
import android.os.AsyncTask;
import com.tangem.data.network.request.ExchangeRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ilia on 04.12.2017.
*/
public class ExchangeTask extends AsyncTask<ExchangeRequest, Void, List<ExchangeRequest>> {
public ExchangeTask()
{
}
protected List<ExchangeRequest> doInBackground(ExchangeRequest... requests) {
List<ExchangeRequest> result = new ArrayList<>();
for (int i = 0; i < requests.length; i++) {
result.add(requests[i]);
}
for (ExchangeRequest request: result)
{
HttpURLConnection httpcon = null;
try {
URL url = new URL("https://api.coinmarketcap.com/v1/ticker/?convert=USD&lmit=10");
httpcon = (HttpURLConnection) url.openConnection();
httpcon.setRequestMethod("GET");
httpcon.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpcon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
request.answerData = response.toString();
} catch (Exception e) {
request.error = e.getMessage();
} finally {
httpcon.disconnect();
}
}
return result;
}
}

View file

@ -1,70 +0,0 @@
package com.tangem.data.network.task;
import android.os.AsyncTask;
import android.util.Log;
import com.tangem.data.network.request.FeeRequest;
import com.tangem.domain.wallet.SharedData;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ilia on 04.12.2017.
*/
public class FeeTask extends AsyncTask<FeeRequest, Void, List<FeeRequest>> {
public SharedData sharedCounter = null;
public FeeTask(SharedData sharedData)
{
sharedCounter = sharedData;
}
protected List<FeeRequest> doInBackground(FeeRequest... requests) {
List<FeeRequest> result = new ArrayList<>();
for (int i = 0; i < requests.length; i++) {
result.add(requests[i]);
}
for (FeeRequest request: result)
{
HttpURLConnection httpcon = null;
try {
URL url = new URL("https://estimatefee.com/n/"+String.valueOf(request.getBlockCount()));
httpcon = (HttpURLConnection) url.openConnection();
httpcon.setRequestMethod("GET");
Log.i("scscsccsw222", String.valueOf(request.getBlockCount()));
httpcon.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpcon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
request.answerData = response.toString();
} catch (Exception e) {
request.error = e.getMessage();
} finally {
httpcon.disconnect();
}
}
return result;
}
}

View file

@ -1,131 +0,0 @@
package com.tangem.data.network.task;
/**
* Created by Ilia on 19.12.2017.
*/
import android.os.AsyncTask;
import com.tangem.domain.wallet.Blockchain;
import com.tangem.data.network.request.InfuraRequest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by Ilia on 04.12.2017.
*/
public class InfuraTask extends AsyncTask<InfuraRequest, Void, List<InfuraRequest>> {
private Exception exception;
private Blockchain blockchain;
public InfuraTask(Blockchain blockchainNet) {
blockchain = blockchainNet;
}
boolean useOurNode = false;
protected List<InfuraRequest> doInBackground(InfuraRequest... requests) {
List<InfuraRequest> result = new ArrayList<>();
for (int i = 0; i < requests.length; i++) {
result.add(requests[i]);
}
for (InfuraRequest request : result) {
HttpURLConnection httpcon = null;
try {
URL url = new URL("https://rinkeby.infura.io/AfWg0tmYEX5Kukn2UkKV");
if (blockchain == Blockchain.Ethereum || blockchain == Blockchain.Token) {
if (useOurNode) {
URL tmp = new URL("http://52.230.23.88");
url = new URL(tmp.getProtocol(), tmp.getHost(), 27172, tmp.getFile());
} else
url = new URL("https://mainnet.infura.io/AfWg0tmYEX5Kukn2UkKV");
}
if (useOurNode) {
httpcon = (HttpURLConnection) url.openConnection();
} else {
httpcon = (HttpsURLConnection) url.openConnection();
}
if (httpcon == null) {
request.error = String.format("Cann't connect to %s", url.getHost());
return result;
}
httpcon.setRequestMethod("POST");
httpcon.setRequestProperty("Content-Type", "application/json");
String params = request.getAsString();
OutputStream os = httpcon.getOutputStream();
if (os == null) {
request.error = String.format("Cann't recieve data from %s", url.getHost());
return result;
}
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
if (writer == null) {
request.error = String.format("Cann't send data to %s", url.getHost());
}
writer.write(params);
writer.flush();
writer.close();
os.close();
httpcon.connect();
request.getParams();
System.out.println("code:" + httpcon.getResponseCode());
int code = httpcon.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpcon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
request.answerData = response.toString();
} catch (Exception e) {
this.exception = e;
request.error = e.getMessage();
} finally {
httpcon.disconnect();
}
}
return result;
}
public String getValidationNodeDescription() {
if (blockchain == Blockchain.Ethereum || blockchain == Blockchain.Token) {
if (useOurNode)
return "52.230.23.88:27172";
else
return "Infura, infura.io";
}
return "Infura, rinkeby.infura.io";
}
}

View file

@ -1,42 +0,0 @@
package com.tangem.data.network.task;
import android.os.AsyncTask;
import com.tangem.data.network.request.VerificationServerProtocol;
import java.util.ArrayList;
import java.util.List;
public class VerificationServerTask extends AsyncTask<VerificationServerProtocol.Request, Void, List<VerificationServerProtocol.Request>> {
// public static final String hostURL = "https://tangem-webapp.appspot.com";
public static final String hostURL = "https://verify.tangem.com";
public VerificationServerTask() {
}
protected List<VerificationServerProtocol.Request> doInBackground(VerificationServerProtocol.Request... requests) {
List<VerificationServerProtocol.Request> result = new ArrayList<>();
for (int i = 0; i < requests.length; i++) {
result.add(requests[i]);
}
for (VerificationServerProtocol.Request request : result) {
try {
request.doPost(hostURL);
} catch (Exception e) {
request.error = e.getMessage();
if (request.error == null || request.error.isEmpty()) {
request.error = e.getClass().getName();
}
}
}
return result;
}
public String getValidationNodeDescription() {
return hostURL;
}
}

View file

@ -1,132 +0,0 @@
package com.tangem.data.network.task.confirm_payment;
import android.app.Activity;
import android.view.View;
import com.tangem.data.network.request.FeeRequest;
import com.tangem.data.network.task.FeeTask;
import com.tangem.domain.wallet.SharedData;
import com.tangem.presentation.activity.ConfirmPaymentActivity;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
public class ConnectFeeTask extends FeeTask {
private WeakReference<ConfirmPaymentActivity> reference;
public ConnectFeeTask(ConfirmPaymentActivity context, SharedData sharedData) {
super(sharedData);
reference = new WeakReference<>(context);
}
@Override
protected void onPostExecute(List<FeeRequest> requests) {
super.onPostExecute(requests);
ConfirmPaymentActivity confirmPaymentActivity = reference.get();
for (FeeRequest request : requests) {
if (request.error == null) {
BigDecimal Fee = BigDecimal.ZERO;
try {
try {
String tmpAnswer = request.getAsString();
Fee = new BigDecimal(tmpAnswer); // BTC per 1 kb
} catch (Exception e) {
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
if (errCounter >= sharedCounter.allRequest) {
confirmPaymentActivity.getProgressBar().setVisibility(View.INVISIBLE);
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
} else {
confirmPaymentActivity.getProgressBar().setVisibility(View.INVISIBLE);
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
//FinishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
return;
}
if (Fee.equals(BigDecimal.ZERO)) {
confirmPaymentActivity.getProgressBar().setVisibility(View.INVISIBLE);
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! Wrong data received from the node");
return;
}
long inputCount = request.txSize;
if (inputCount != 0) {
Fee = Fee.multiply(new BigDecimal(inputCount)).divide(new BigDecimal(1024)); // per Kb -> per byte
} else {
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! Tx length unknown");
}
} catch (Exception e) {
e.printStackTrace();
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
if (errCounter >= sharedCounter.allRequest) {
confirmPaymentActivity.getProgressBar().setVisibility(View.INVISIBLE);
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
} else {
confirmPaymentActivity.getProgressBar().setVisibility(View.INVISIBLE);
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
return;
}
confirmPaymentActivity.getProgressBar().setVisibility(View.INVISIBLE);
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(7);
df.setMinimumFractionDigits(3);
df.setGroupingUsed(false);
String strFee = df.format(Fee);
if ((request.getBlockCount() == FeeRequest.MINIMAL) && (confirmPaymentActivity.getMinFee() == null)) {
confirmPaymentActivity.setMinFee(strFee);
confirmPaymentActivity.setMinFeeInInternalUnits(confirmPaymentActivity.getCard().internalUnitsFromString(strFee));
} else if ((request.getBlockCount() == FeeRequest.NORMAL) && (confirmPaymentActivity.getNormalFee() == null)) {
confirmPaymentActivity.setNormalFee(strFee);
} else if ((request.getBlockCount() == FeeRequest.PRIORITY) && (confirmPaymentActivity.getMaxFee() == null)) {
confirmPaymentActivity.setMaxFee(strFee);
}
confirmPaymentActivity.doSetFee(confirmPaymentActivity.getRgFee().getCheckedRadioButtonId());
confirmPaymentActivity.getEtFee().setError(null);
confirmPaymentActivity.setFeeRequestSuccess(true);
if (confirmPaymentActivity.getFeeRequestSuccess() && confirmPaymentActivity.getBalanceRequestSuccess()) {
confirmPaymentActivity.getBtnSend().setVisibility(View.VISIBLE);
}
confirmPaymentActivity.setDtVerified(new Date());
} else {
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
if (errCounter >= sharedCounter.allRequest) {
confirmPaymentActivity.getProgressBar().setVisibility(View.INVISIBLE);
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
} else {
confirmPaymentActivity.getProgressBar().setVisibility(View.INVISIBLE);
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
}
}
}
}

View file

@ -1,120 +0,0 @@
package com.tangem.data.network.task.confirm_payment;
import android.app.Activity;
import android.view.View;
import com.tangem.data.network.request.ElectrumRequest;
import com.tangem.data.network.task.ElectrumTask;
import com.tangem.domain.wallet.SharedData;
import com.tangem.presentation.activity.ConfirmPaymentActivity;
import org.json.JSONException;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.List;
public class ConnectTask extends ElectrumTask {
private WeakReference<ConfirmPaymentActivity> reference;
public ConnectTask(ConfirmPaymentActivity context, String host, int port) {
super(host, port);
reference = new WeakReference<>(context);
}
public ConnectTask(ConfirmPaymentActivity context, String host, int port, SharedData sharedData) {
super(host, port, sharedData);
reference = new WeakReference<>(context);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(List<ElectrumRequest> requests) {
super.onPostExecute(requests);
ConfirmPaymentActivity confirmPaymentActivity = reference.get();
for (ElectrumRequest request : requests) {
try {
if (request.error == null) {
if (request.isMethod(ElectrumRequest.METHOD_GetBalance)) {
try {
confirmPaymentActivity.getEtFee().setText("--");
//String mWalletAddress = request.getParams().getString(0);
if ((request.getResult().getInt("confirmed") + request.getResult().getInt("unconfirmed")) / confirmPaymentActivity.getCard().getBlockchain().getMultiplier() * 1000000.0 < Float.parseFloat(confirmPaymentActivity.getEtAmount().getText().toString())) {
confirmPaymentActivity.getEtFee().setError("Not enough funds");
if (sharedCounter == null) {
confirmPaymentActivity.setBalanceRequestSuccess(false);
confirmPaymentActivity.getBtnSend().setVisibility(View.INVISIBLE);
confirmPaymentActivity.setDtVerified(null);
confirmPaymentActivity.setNodeCheck(false);
} else {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
if (errCounter >= sharedCounter.allRequest) {
confirmPaymentActivity.setBalanceRequestSuccess(false);
confirmPaymentActivity.getBtnSend().setVisibility(View.INVISIBLE);
confirmPaymentActivity.setDtVerified(null);
confirmPaymentActivity.setNodeCheck(false);
}
}
} else {
confirmPaymentActivity.getEtFee().setError(null);
confirmPaymentActivity.setBalanceRequestSuccess(true);
if (confirmPaymentActivity.getFeeRequestSuccess() && confirmPaymentActivity.getBalanceRequestSuccess()) {
confirmPaymentActivity.getBtnSend().setVisibility(View.VISIBLE);
}
confirmPaymentActivity.setDtVerified(new Date());
confirmPaymentActivity.setNodeCheck(true);
}
} catch (JSONException e) {
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
if (errCounter >= sharedCounter.allRequest) {
e.printStackTrace();
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot check balance! No connection with blockchain nodes");
}
} else {
e.printStackTrace();
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot check balance! No connection with blockchain nodes");
}
}
} else if (request.isMethod(ElectrumRequest.METHOD_GetFee)) {
if (request.getResultString() == "-1") {
confirmPaymentActivity.getEtFee().setText("3");
}
}
} else {
// etFee.setError(request.error);
// btnSend.setVisibility(View.INVISIBLE);
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
if (errCounter >= sharedCounter.allRequest) {
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
} else {
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
return;
}
} catch (JSONException e) {
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
if (errCounter >= sharedCounter.allRequest) {
e.printStackTrace();
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
} else {
e.printStackTrace();
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Cannot calculate fee! No connection with blockchain nodes");
}
}
}
}
}

View file

@ -1,80 +0,0 @@
package com.tangem.data.network.task.confirm_payment;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import com.tangem.data.network.request.InfuraRequest;
import com.tangem.data.network.task.InfuraTask;
import com.tangem.domain.wallet.Blockchain;
import com.tangem.presentation.activity.ConfirmPaymentActivity;
import org.json.JSONException;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
public class ETHRequestTask extends InfuraTask {
private WeakReference<ConfirmPaymentActivity> reference;
public ETHRequestTask(ConfirmPaymentActivity context, Blockchain blockchain) {
super(blockchain);
reference = new WeakReference<>(context);
}
@Override
protected void onPostExecute(List<InfuraRequest> requests) {
super.onPostExecute(requests);
ConfirmPaymentActivity confirmPaymentActivity = reference.get();
for (InfuraRequest request : requests) {
try {
Long price = 0L;
if (request.error == null) {
if (request.isMethod(InfuraRequest.METHOD_ETH_GetGasPrice)) {
try {
String gasPrice = request.getResultString();
Log.i("Gas Price 1", gasPrice);
gasPrice = gasPrice.substring(2);
BigInteger l = new BigInteger(gasPrice, 16);
Log.i("Gas Price 2", gasPrice);
BigInteger GasLimit = confirmPaymentActivity.getCard().getBlockchain() == Blockchain.Token ? BigInteger.valueOf(60000) : BigInteger.valueOf(21000);
String MinFeeInGwei = confirmPaymentActivity.getCard().getAmountInGwei(String.valueOf(l.multiply(GasLimit)));
String NormalFeeInGwei = confirmPaymentActivity.getCard().getAmountInGwei(String.valueOf(l.multiply(BigInteger.valueOf(12)).divide(BigInteger.valueOf(10).multiply(GasLimit))));
String MaxFeeInGwei = confirmPaymentActivity.getCard().getAmountInGwei(String.valueOf(l.multiply(BigInteger.valueOf(15)).divide(BigInteger.valueOf(10).multiply(GasLimit))));
Log.i("Min Fee Gwei", MinFeeInGwei);
confirmPaymentActivity.setMinFee(MinFeeInGwei);
confirmPaymentActivity.setNormalFee(NormalFeeInGwei);
confirmPaymentActivity.setMaxFee(MaxFeeInGwei);
confirmPaymentActivity.getEtFee().setText(NormalFeeInGwei);
confirmPaymentActivity.getEtFee().setError(null);
confirmPaymentActivity.getBtnSend().setVisibility(View.VISIBLE);
confirmPaymentActivity.setFeeRequestSuccess(true);
confirmPaymentActivity.setBalanceRequestSuccess(true);
confirmPaymentActivity.setDtVerified(new Date());
confirmPaymentActivity.setMinFeeInInternalUnits(confirmPaymentActivity.getCard().internalUnitsFromString(NormalFeeInGwei));
} catch (JSONException e) {
e.printStackTrace();
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Can't calculate fee! No connection with blockchain nodes");
}
}
} else {
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Can't calculate fee! No connection with blockchain nodes");
}
} catch (JSONException e) {
e.printStackTrace();
confirmPaymentActivity.finishActivityWithError(Activity.RESULT_CANCELED, "Can't calculate fee! No connection with blockchain nodes");
}
}
}
}

View file

@ -1,124 +0,0 @@
package com.tangem.data.network.task.loaded_wallet;
import android.util.Log;
import com.tangem.data.network.request.InfuraRequest;
import com.tangem.data.network.task.InfuraTask;
import com.tangem.domain.wallet.Blockchain;
import com.tangem.presentation.fragment.LoadedWallet;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.util.List;
public class ETHRequestTask extends InfuraTask {
private WeakReference<LoadedWallet> reference;
public ETHRequestTask(LoadedWallet context, Blockchain blockchain) {
super(blockchain);
reference = new WeakReference<>(context);
}
@Override
protected void onPostExecute(List<InfuraRequest> requests) {
super.onPostExecute(requests);
LoadedWallet loadedWallet = reference.get();
for (InfuraRequest request : requests) {
try {
if (request.error == null) {
if (request.isMethod(InfuraRequest.METHOD_ETH_GetBalance)) {
try {
String balanceCap = request.getResultString();
balanceCap = balanceCap.substring(2);
BigInteger l = new BigInteger(balanceCap, 16);
BigInteger d = l.divide(new BigInteger("1000000000000000000", 10));
Long balance = d.longValue();
loadedWallet.getCard().setBalanceConfirmed(balance);
loadedWallet.getCard().setBalanceUnconfirmed(0L);
if (loadedWallet.getCard().getBlockchain() != Blockchain.Token)
loadedWallet.getCard().setDecimalBalance(l.toString(10));
loadedWallet.getCard().setDecimalBalanceAlter(l.toString(10));
} catch (JSONException e) {
e.printStackTrace();
}
} else if (request.isMethod(InfuraRequest.METHOD_ETH_Call)) {
try {
String balanceCap = request.getResultString();
balanceCap = balanceCap.substring(2);
BigInteger l = new BigInteger(balanceCap, 16);
Long balance = l.longValue();
if (l.compareTo(BigInteger.ZERO) == 0) {
loadedWallet.getCard().setBlockchainID(Blockchain.Ethereum.getID());
loadedWallet.getCard().addTokenToBlockchainName();
loadedWallet.getSrlLoadedWallet().setRefreshing(false);
loadedWallet.refresh();
return;
}
loadedWallet.getCard().setBalanceConfirmed(balance);
loadedWallet.getCard().setBalanceUnconfirmed(0L);
loadedWallet.getCard().setDecimalBalance(l.toString(10));
} catch (JSONException e) {
e.printStackTrace();
}
} else if (request.isMethod(InfuraRequest.METHOD_ETH_GetOutTransactionCount)) {
try {
String nonce = request.getResultString();
nonce = nonce.substring(2);
BigInteger count = new BigInteger(nonce, 16);
loadedWallet.getCard().setConfirmedTXCount(count);
} catch (JSONException e) {
e.printStackTrace();
}
} else if (request.isMethod(InfuraRequest.METHOD_ETH_SendRawTransaction)) {
try {
String hashTX = "";
try {
String tmp = request.getResultString();
hashTX = tmp;
} catch (JSONException e) {
JSONObject msg = request.getAnswer();
JSONObject err = msg.getJSONObject("error");
hashTX = err.getString("message");
return;
}
if (hashTX.startsWith("0x") || hashTX.startsWith("0X")) {
hashTX = hashTX.substring(2);
}
BigInteger bigInt = new BigInteger(hashTX, 16); //TODO: очень плохой способ
Log.e("TX_RESULT", hashTX);
BigInteger nonce = loadedWallet.getCard().getConfirmedTXCount();
nonce.add(BigInteger.valueOf(1));
loadedWallet.getCard().setConfirmedTXCount(nonce);
Log.e("TX_RESULT", hashTX);
} catch (Exception e) {
e.printStackTrace();
}
}
loadedWallet.updateViews();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
loadedWallet.getSrlLoadedWallet().setRefreshing(false);
}
}

View file

@ -1,74 +0,0 @@
package com.tangem.data.network.task.loaded_wallet;
import com.tangem.data.network.request.ExchangeRequest;
import com.tangem.data.network.task.ExchangeTask;
import com.tangem.presentation.fragment.LoadedWallet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.List;
public class RateInfoTask extends ExchangeTask {
private WeakReference<LoadedWallet> reference;
public RateInfoTask(LoadedWallet context) {
reference = new WeakReference<>(context);
}
protected void onPostExecute(List<ExchangeRequest> requests) {
super.onPostExecute(requests);
try {
LoadedWallet loadedWallet = reference.get();
for (ExchangeRequest request : requests) {
if (request.error == null) {
try {
JSONArray arr = request.getAnswerList();
for (int i = 0; i < arr.length(); ++i) {
JSONObject obj = arr.getJSONObject(i);
String currency = obj.getString("id");
boolean stop = false;
boolean stopAlter = false;
if (currency.equals(request.currency)) {
String usd = obj.getString("price_usd");
Float rate = Float.valueOf(usd);
loadedWallet.getCard().setRate(rate);
loadedWallet.updateViews();
stop = true;
}
if (currency.equals(request.currencyAlter)) {
String usd = obj.getString("price_usd");
Float rate = Float.valueOf(usd);
loadedWallet.getCard().setRateAlter(rate);
loadedWallet.updateViews();
stopAlter = true;
}
if (stop && stopAlter) {
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}

View file

@ -1,192 +0,0 @@
package com.tangem.data.network.task.loaded_wallet;
import android.os.AsyncTask;
import com.tangem.data.network.request.ElectrumRequest;
import com.tangem.data.network.task.ElectrumTask;
import com.tangem.domain.wallet.CoinEngine;
import com.tangem.domain.wallet.CoinEngineFactory;
import com.tangem.domain.wallet.SharedData;
import com.tangem.domain.wallet.TangemCard;
import com.tangem.presentation.fragment.LoadedWallet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.List;
public class UpdateWalletInfoTask extends ElectrumTask {
private WeakReference<LoadedWallet> reference;
public UpdateWalletInfoTask(LoadedWallet context, String host, int port) {
super(host, port);
reference = new WeakReference<>(context);
}
public UpdateWalletInfoTask(LoadedWallet context, String host, int port, SharedData sharedData) {
super(host, port, sharedData);
reference = new WeakReference<>(context);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
// @Override
// protected void onCancelled() {
// super.onCancelled();
// LoadedWallet loadedWallet = reference.get();
//
// loadedWallet.updateTasks.remove(this);
// if (loadedWallet.updateTasks.size() == 0) loadedWallet.mSwipeRefreshLayout.setRefreshing(false);
// }
@Override
protected void onPostExecute(List<ElectrumRequest> requests) {
super.onPostExecute(requests);
LoadedWallet loadedWallet = reference.get();
// Log.i("RequestWalletInfoTask", "onPostExecute[" + String.valueOf(loadedWallet.updateTasks.size()) + "]");
// loadedWallet.updateTasks.remove(this);
try {
CoinEngine engine = CoinEngineFactory.create(loadedWallet.getCard().getBlockchain());
for (ElectrumRequest request : requests) {
try {
if (request.error == null) {
// get balance
if (request.isMethod(ElectrumRequest.METHOD_GetBalance)) {
try {
String walletAddress = request.getParams().getString(0);
Long confBalance = request.getResult().getLong("confirmed");
Long unconfirmedBalance = request.getResult().getLong("unconfirmed");
loadedWallet.getCard().setBalanceReceived(true);
if (sharedCounter != null) {
boolean notEqualBalance = sharedCounter.updatePayload(new BigDecimal(String.valueOf(confBalance)));
if (notEqualBalance)
loadedWallet.getCard().setIsBalanceEqual(false);
int counter = sharedCounter.requestCounter.incrementAndGet();
if (counter != 1) {
continue;
}
}
loadedWallet.getCard().setBalanceConfirmed(confBalance);
loadedWallet.getCard().setBalanceUnconfirmed(unconfirmedBalance);
loadedWallet.getCard().setDecimalBalance(String.valueOf(confBalance));
loadedWallet.getCard().setValidationNodeDescription(getValidationNodeDescription());
} catch (JSONException e) {
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
loadedWallet.getCard().incFailedBalanceRequestCounter();
if (errCounter >= sharedCounter.allRequest) {
e.printStackTrace();
engine.switchNode(loadedWallet.getCard());
}
} else {
e.printStackTrace();
engine.switchNode(loadedWallet.getCard());
}
}
}
// send transaction
else if (request.isMethod(ElectrumRequest.METHOD_SendTransaction)) {
try {
String hashTX = request.getResultString();
} catch (JSONException e) {
e.printStackTrace();
engine.switchNode(loadedWallet.getCard());
}
}
// list unspent
else if (request.isMethod(ElectrumRequest.METHOD_ListUnspent)) {
try {
String mWalletAddress = request.getParams().getString(0);
JSONArray jsUnspentArray = request.getResultArray();
try {
loadedWallet.getCard().getUnspentTransactions().clear();
for (int i = 0; i < jsUnspentArray.length(); i++) {
JSONObject jsUnspent = jsUnspentArray.getJSONObject(i);
TangemCard.UnspentTransaction trUnspent = new TangemCard.UnspentTransaction();
trUnspent.txID = jsUnspent.getString("tx_hash");
trUnspent.Amount = jsUnspent.getInt("value");
trUnspent.Height = jsUnspent.getInt("height");
loadedWallet.getCard().getUnspentTransactions().add(trUnspent);
}
} catch (JSONException e) {
e.printStackTrace();
engine.switchNode(loadedWallet.getCard());
}
for (int i = 0; i < jsUnspentArray.length(); i++) {
JSONObject jsUnspent = jsUnspentArray.getJSONObject(i);
Integer height = jsUnspent.getInt("height");
String hash = jsUnspent.getString("tx_hash");
if (height != -1) {
String nodeAddress = engine.getNode(loadedWallet.getCard());
int nodePort = engine.getNodePort(loadedWallet.getCard());
engine.switchNode(loadedWallet.getCard());
UpdateWalletInfoTask updateWalletInfoTask = new UpdateWalletInfoTask(loadedWallet, nodeAddress, nodePort);
// loadedWallet.updateTasks.add(updateWalletInfoTask);
updateWalletInfoTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ElectrumRequest.getTransaction(mWalletAddress, hash));
}
}
} catch (JSONException e) {
e.printStackTrace();
engine.switchNode(loadedWallet.getCard());
}
}
// get transaction
else if (request.isMethod(ElectrumRequest.METHOD_GetTransaction)) {
try {
String txHash = request.txHash;
String raw = request.getResultString();
List<TangemCard.UnspentTransaction> listTx = loadedWallet.getCard().getUnspentTransactions();
for (TangemCard.UnspentTransaction tx : listTx) {
if (tx.txID.equals(txHash))
tx.Raw = raw;
}
} catch (JSONException e) {
e.printStackTrace();
engine.switchNode(loadedWallet.getCard());
}
}
loadedWallet.updateViews();
} else {
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
loadedWallet.getCard().incFailedBalanceRequestCounter();
if (errCounter >= sharedCounter.allRequest)
engine.switchNode(loadedWallet.getCard());
} else
engine.switchNode(loadedWallet.getCard());
}
} catch (JSONException e) {
if (sharedCounter != null) {
int errCounter = sharedCounter.errorRequest.incrementAndGet();
loadedWallet.getCard().incFailedBalanceRequestCounter();
if (errCounter >= sharedCounter.allRequest)
e.printStackTrace();
} else {
e.printStackTrace();
}
}
}
loadedWallet.getSrlLoadedWallet().setRefreshing(false);
} catch (NullPointerException e) {
e.printStackTrace();
if (reference.get() != null)
reference.get().getSrlLoadedWallet().setRefreshing(false);
}
}
}

View file

@ -1,115 +0,0 @@
package com.tangem.data.network.task.send_transaction;
import android.util.Log;
import com.tangem.data.network.request.ElectrumRequest;
import com.tangem.data.network.task.ElectrumTask;
import com.tangem.domain.wallet.Blockchain;
import com.tangem.domain.wallet.CoinEngine;
import com.tangem.domain.wallet.CoinEngineFactory;
import com.tangem.domain.wallet.SharedData;
import com.tangem.domain.wallet.TangemCard;
import com.tangem.presentation.activity.SendTransactionActivity;
import org.json.JSONException;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.util.List;
public class ConnectTask extends ElectrumTask {
private WeakReference<SendTransactionActivity> reference;
private int remaining_attempts;
private void CreateChildTask(TangemCard mCard, String tx, String error_message) {
if (remaining_attempts > 0) {
remaining_attempts--;
CoinEngine engine = CoinEngineFactory.create(mCard.getBlockchain());
if (mCard.getBlockchain() == Blockchain.Bitcoin || mCard.getBlockchain() == Blockchain.BitcoinTestNet) {
String nodeAddress = engine.getNode(mCard);
int nodePort = engine.getNodePort(mCard);
ConnectTask connectTask = new ConnectTask(reference.get(), nodeAddress, nodePort, remaining_attempts);
connectTask.execute(ElectrumRequest.broadcast(mCard.getWallet(), tx));
} else if (mCard.getBlockchain() == Blockchain.BitcoinCash || mCard.getBlockchain() == Blockchain.BitcoinCashTestNet) {
String nodeAddress = engine.getNode(mCard);
int nodePort = engine.getNodePort(mCard);
ConnectTask connectTask = new ConnectTask(reference.get(), nodeAddress, nodePort, remaining_attempts);
connectTask.execute(ElectrumRequest.broadcast(mCard.getWallet(), tx));
}
} else {
reference.get().finishWithError(error_message);
}
}
public ConnectTask(SendTransactionActivity context, String host, int port, int attempts) {
super(host, port);
reference = new WeakReference<>(context);
remaining_attempts = attempts;
}
public ConnectTask(SendTransactionActivity context, String host, int port, int attempts, SharedData sharedData) {
super(host, port, sharedData);
reference = new WeakReference<>(context);
remaining_attempts = attempts;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(List<ElectrumRequest> requests) {
super.onPostExecute(requests);
SendTransactionActivity sendTransactionActivity = reference.get();
CoinEngine engine = CoinEngineFactory.create(Blockchain.Bitcoin);
for (ElectrumRequest request : requests) {
try {
if (request.error == null) {
if (request.isMethod(ElectrumRequest.METHOD_SendTransaction)) {
try {
String hashTX = request.getResultString();
try {
if (hashTX.startsWith("0x") || hashTX.startsWith("0X")) {
hashTX = hashTX.substring(2);
}
Log.e("TX_RESULT", hashTX);
sendTransactionActivity.finishWithSuccess();
} catch (Exception e) {
engine.switchNode(null);
// sendTransactionActivity.finishWithError(hashTX);
CreateChildTask(sendTransactionActivity.getCard(), request.TX, hashTX);
}
} catch (JSONException e) {
e.printStackTrace();
engine.switchNode(null);
// sendTransactionActivity.finishWithError(e.toString());
CreateChildTask(sendTransactionActivity.getCard(), request.TX, e.toString());
}
}
} else {
engine.switchNode(null);
// sendTransactionActivity.finishWithError(request.error);
CreateChildTask(sendTransactionActivity.getCard(), request.TX, request.error);
}
} catch (JSONException e) {
e.printStackTrace();
engine.switchNode(null);
// sendTransactionActivity.finishWithError(e.toString());
CreateChildTask(sendTransactionActivity.getCard(), request.TX, e.toString());
}
}
}
}

View file

@ -1,76 +0,0 @@
package com.tangem.data.network.task.send_transaction;
import android.util.Log;
import com.tangem.data.network.request.InfuraRequest;
import com.tangem.data.network.task.InfuraTask;
import com.tangem.domain.wallet.Blockchain;
import com.tangem.presentation.activity.SendTransactionActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.util.List;
public class ETHRequestTask extends InfuraTask {
private WeakReference<SendTransactionActivity> reference;
public ETHRequestTask(SendTransactionActivity context, Blockchain blockchain) {
super(blockchain);
reference = new WeakReference<>(context);
}
@Override
protected void onPostExecute(List<InfuraRequest> requests) {
super.onPostExecute(requests);
SendTransactionActivity sendTransactionActivity = reference.get();
for (InfuraRequest request : requests) {
try {
if (request.error == null) {
if (request.isMethod(InfuraRequest.METHOD_ETH_SendRawTransaction)) {
try {
String hashTX = "";
try {
String tmp = request.getResultString();
hashTX = tmp;
} catch (JSONException e) {
JSONObject msg = request.getAnswer();
JSONObject err = msg.getJSONObject("error");
hashTX = err.getString("message");
Log.e("Send_TX_Error:", hashTX);
sendTransactionActivity.finishWithError(hashTX);
return;
}
try {
if (hashTX.startsWith("0x") || hashTX.startsWith("0X")) {
hashTX = hashTX.substring(2);
}
BigInteger nonce = sendTransactionActivity.getCard().getConfirmedTXCount();
nonce.add(BigInteger.valueOf(1));
sendTransactionActivity.getCard().setConfirmedTXCount(nonce);
Log.e("TX_RESULT", hashTX);
sendTransactionActivity.finishWithSuccess();
} catch (Exception e) {
sendTransactionActivity.finishWithError(hashTX);
}
} catch (JSONException e) {
e.printStackTrace();
sendTransactionActivity.finishWithError(e.toString());
}
}
} else if (request.error != null) {
sendTransactionActivity.finishWithError(request.error);
}
} catch (JSONException e) {
e.printStackTrace();
sendTransactionActivity.finishWithError(e.toString());
}
}
}
}

View file

@ -23,4 +23,5 @@ public interface AppComponent {
@Named(Server.ApiCoinmarket.URL_COINMARKET)
Retrofit getRetrofitCoinmarketcap();
}