diff --git a/app/build.gradle b/app/build.gradle index 10b187ccff..d3fe8f8d93 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -40,9 +40,15 @@ android { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } + packagingOptions { + pickFirst('META-INF/proguard/okhttp3.pro') + } buildToolsVersion '28.0.3' } +repositories { + maven { url "https://jitpack.io" } +} dependencies { implementation project(':tangemcard-common') implementation project(':tangemcard-android') @@ -72,5 +78,5 @@ dependencies { implementation 'io.reactivex.rxjava2:rxjava:2.2.0' implementation 'io.reactivex.rxjava2:rxandroid:2.0.1' implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0' - + implementation 'com.github.stellar:java-stellar-sdk:0.4.1' } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/data/Blockchain.java b/app/src/main/java/com/tangem/data/Blockchain.java index 5ad40fedc9..cc5828ecda 100644 --- a/app/src/main/java/com/tangem/data/Blockchain.java +++ b/app/src/main/java/com/tangem/data/Blockchain.java @@ -6,25 +6,24 @@ import com.tangem.tangemcard.R; * Created by dvol on 06.08.2017. */ public enum Blockchain { - Unknown("", "", 1.0, R.drawable.ic_logo_unknown, ""), - Bitcoin("BTC", "BTC", 100000000.0, R.drawable.ic_logo_bitcoin, "Bitcoin"), - BitcoinTestNet("BTC/test", "BTC", 100000000.0, R.drawable.ic_logo_bitcoin_testnet, "Bitcoin Testnet"), - 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"), - Litecoin("LTC", "LTC", 100000000.0, R.drawable.ic_logo_bitcoin, "Litecoin"); - - Blockchain(String ID, String currency, double multiplier, int imageResource, String officialName) { + Unknown("", "", R.drawable.ic_logo_unknown, ""), + Bitcoin("BTC", "BTC", R.drawable.ic_logo_bitcoin, "Bitcoin"), + BitcoinTestNet("BTC/test", "BTC", R.drawable.ic_logo_bitcoin_testnet, "Bitcoin Testnet"), + Ethereum("ETH", "ETH", R.drawable.ic_logo_ethereum, "Ethereum"), + EthereumTestNet("ETH/test", "ETH", R.drawable.ic_logo_ethereum_testnet, "Ethereum Testnet"), + Token("Token", "ERC20", R.drawable.ic_logo_bat_token, "Ethereum"), + BitcoinCash("BCH", "BCH", R.drawable.ic_logo_bitcoin_cash, "Bitcoin Cash"), + Litecoin("LTC", "LTC", R.drawable.ic_logo_bitcoin, "Litecoin"), + Stellar("XLM", "XLM", R.drawable.ic_logo_stellar, "Stellar Lumens"), + StellarTestNet("XLM/test", "XLM", R.drawable.ic_logo_bitcoin, "Stellar Lumens"); + Blockchain(String ID, String currency, int imageResource, String officialName) { mID = ID; mCurrency = currency; -// mMultiplier = multiplier; mImageResource = imageResource; mOfficialName = officialName; } private String mID, mOfficialName; - //private double mMultiplier; private String mCurrency; private int mImageResource; @@ -36,10 +35,6 @@ public enum Blockchain { return mOfficialName; } -// public double getMultiplier() { -// return mMultiplier; -// } - public String getCurrency() { return mCurrency; } @@ -83,6 +78,7 @@ public enum Blockchain { return resourceId; } + //TODO - ??? public static int getLogoImageResource(String blockchainID, String symbolName) { switch (blockchainID) { case "BTC": @@ -96,6 +92,9 @@ public enum Blockchain { case "ETH": return R.drawable.ic_logo_ethereum; + + case "XLM": + return R.drawable.ic_logo_stellar; } return R.drawable.tangem2; } diff --git a/app/src/main/java/com/tangem/data/network/ServerApiStellar.java b/app/src/main/java/com/tangem/data/network/ServerApiStellar.java new file mode 100644 index 0000000000..dd95612984 --- /dev/null +++ b/app/src/main/java/com/tangem/data/network/ServerApiStellar.java @@ -0,0 +1,151 @@ +package com.tangem.data.network; + +import android.util.Log; + +import com.tangem.App; +import com.tangem.data.Blockchain; +import com.tangem.domain.wallet.TangemContext; +import com.tangem.wallet.R; + +import org.stellar.sdk.Network; +import org.stellar.sdk.Server; + +import java.io.IOException; + +import io.reactivex.Observable; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.observers.DefaultObserver; +import io.reactivex.schedulers.Schedulers; + +/** + * Request processor for Electrum Api + * Every request live cycle: + * 1. In application create request and call {@link ServerApiStellar}.requestData(..) + * 2. Try send every request for max 4 times, + * 3. If all 4 times fail call DefaultObserver.onError (defined in .requestData(..)) and than + * {@link Listener}.onFail(...) callback + * Error can be acquired with {@link StellarRequest}.getError() method + * 4. If request network communication finished successfully then call DefaultObserver.onComplete (defined in .requestData) and than + * {@link Listener}.onSuccess(...) callback + */ +public class ServerApiStellar { + private static String TAG = ServerApiStellar.class.getSimpleName(); + + /** + * TCP, SSL + * Used in BTC, BCH + */ + private Listener listener; + + private int requestsCount=0; + + public boolean isRequestsSequenceCompleted() { + Log.i(TAG, String.format("isRequestsSequenceCompleted: %s (%d requests left)", String.valueOf(requestsCount <= 0), requestsCount)); + return requestsCount <= 0; + } + + /** + * Interface for notification every request result + */ + public interface Listener { + + /** + * Notify that request processing was successful + * @param stellarRequest - processed request containing received answer {@see stellarRequest.getAnswer() method} + */ + void onSuccess(StellarRequest.Base stellarRequest); + /** + * Notify that request processing was successful + * @param stellarRequest - processed request containing occurred error {@see stellarRequest.getError() method} + */ + void onFail(StellarRequest.Base stellarRequest); + } + + /** + * Set notificaion listener + * @param listener + */ + public void setListener(Listener listener) { + this.listener = listener; + } + + + /** + * Start process request + * @param ctx + * @param stellarRequest + */ + public void requestData(TangemContext ctx, StellarRequest.Base stellarRequest) { + requestsCount++; + Log.i(TAG, String.format("New request[%d]: %s", requestsCount,stellarRequest.getClass().getSimpleName())); + Observable stellarObserver = Observable.just(stellarRequest) + .doOnNext(stellarRequest1 -> doStellarRequest(ctx, stellarRequest)) + +// .flatMap(stellarRequest1 -> { +// if (stellarRequest1.answerData == null) { +// Log.e(TAG, "NullPointerException " + stellarRequest.getMethod()); +// return Observable.error(new NullPointerException()); +// } else +// return Observable.just(stellarRequest1); +// }) +// + .retryWhen(errors -> errors + .filter(throwable -> throwable instanceof IOException) + .zipWith(Observable.range(1, 4), (n, i) -> i)) + + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()); + stellarObserver.subscribe(new DefaultObserver() { + + @Override + public void onNext(StellarRequest.Base stellarRequest) { + + } + + @Override + public void onError(Throwable e) { + requestsCount--; + Log.e(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onError " + e.getMessage()); + Log.e(TAG, String.format("%d requests left in processing",requestsCount)); + stellarRequest.setError(ctx.getString(R.string.cannot_obtain_data_from_blockchain)); + //setErrorOccurred(e.getMessage());//; + listener.onFail(stellarRequest); + } + + /** + * Called after completion request processing + */ + @Override + public void onComplete() { + requestsCount--; + Log.e(TAG, String.format("%d requests left in processing",requestsCount)); + if (stellarRequest.getError() != null) { + Log.i(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onComplete, error!=null"); + listener.onFail(stellarRequest); + } else { + Log.e(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onComplete, error==null"); + listener.onSuccess(stellarRequest); + } + } + + }); + } + + private void doStellarRequest(TangemContext ctx, StellarRequest.Base stellarRequest) throws IOException { + stellarRequest.setError(null); + try { + if( ctx.getBlockchain()==Blockchain.StellarTestNet ) { + Network.useTestNetwork(); + } + Server server = new Server(ServerURL.API_STELLAR); + stellarRequest.process(server); + } + catch (Exception e) + { + e.printStackTrace(); + stellarRequest.setError(App.getInstance().getString(R.string.cannot_obtain_data_from_blockchain_communication_error)); + throw e; + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/data/network/ServerURL.java b/app/src/main/java/com/tangem/data/network/ServerURL.java index 297b3ee60c..4703dd6436 100644 --- a/app/src/main/java/com/tangem/data/network/ServerURL.java +++ b/app/src/main/java/com/tangem/data/network/ServerURL.java @@ -6,4 +6,5 @@ class ServerURL { static final String API_INFURA = "https://mainnet.infura.io/v3/"; static final String API_ESTIMATEFEE = "https://estimatefee.com/"; static final String API_UPDATE_VERSION = "https://raw.githubusercontent.com/"; + static final String API_STELLAR = "https://horizon-testnet.stellar.org"; } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/data/network/StellarRequest.java b/app/src/main/java/com/tangem/data/network/StellarRequest.java new file mode 100644 index 0000000000..03a6fe90dc --- /dev/null +++ b/app/src/main/java/com/tangem/data/network/StellarRequest.java @@ -0,0 +1,72 @@ +package com.tangem.data.network; + +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.Server; +import org.stellar.sdk.Transaction; +import org.stellar.sdk.responses.AccountResponse; +import org.stellar.sdk.responses.SubmitTransactionResponse; + +import java.io.IOException; + +/** + * Created by dvol on 16.07.2017. + */ + +public class StellarRequest { + + public static abstract class Base { + private String error = null; + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public abstract void process(Server server) throws IOException; + } + + public static class Balance extends Base { + public KeyPair accountKeyPair; + public AccountResponse accountResponse; + + public Balance(String walletAddress) + { + accountKeyPair=KeyPair.fromAccountId(walletAddress); + } + + @Override + public void process(Server server) throws IOException { + accountResponse=server.accounts().account(accountKeyPair); + } + } + + public static class SubmitTransaction extends Base { +// public KeyPair sourceAccount; +// public KeyPair targetAccount; + public Transaction transaction; + public SubmitTransactionResponse response; + + public SubmitTransaction(Transaction transaction) { + this.transaction=transaction; + } + + @Override + public void process(Server server) throws IOException { +// // First, check to make sure that the destination account exists. +// // You could skip this, but if the account does not exist, you will be charged +// // the transaction fee when the transaction fails. +// // It will throw HttpResponseException if account does not exist or there was another error. +// server.accounts().account(targetAccount); +// +// // If there was no error, load up-to-date information on your account. +// AccountResponse sourceAccount = server.accounts().account(sourceAccount); + + // And finally, send it off to Stellar! + response = server.submitTransaction(transaction); + } + } + + +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/domain/wallet/CoinEngineFactory.kt b/app/src/main/java/com/tangem/domain/wallet/CoinEngineFactory.kt index 951b7eb457..7685b20986 100644 --- a/app/src/main/java/com/tangem/domain/wallet/CoinEngineFactory.kt +++ b/app/src/main/java/com/tangem/domain/wallet/CoinEngineFactory.kt @@ -8,6 +8,7 @@ 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 +import com.tangem.domain.wallet.xlm.XlmEngine /** * Factory for create specific engine @@ -44,6 +45,8 @@ object CoinEngineFactory { TokenEngine(context) else if (Blockchain.Litecoin == context.blockchain) LtcEngine(context) + else if (Blockchain.Stellar == context.blockchain || Blockchain.StellarTestNet == context.blockchain) + XlmEngine(context) else return null } catch (e: Exception) { diff --git a/app/src/main/java/com/tangem/domain/wallet/xlm/XlmData.java b/app/src/main/java/com/tangem/domain/wallet/xlm/XlmData.java new file mode 100644 index 0000000000..a4ca60c528 --- /dev/null +++ b/app/src/main/java/com/tangem/domain/wallet/xlm/XlmData.java @@ -0,0 +1,81 @@ +package com.tangem.domain.wallet.xlm; + +import android.os.Bundle; +import android.util.Log; + +import com.tangem.domain.wallet.CoinData; +import com.tangem.domain.wallet.CoinEngine; + +import org.stellar.sdk.Account; +import org.stellar.sdk.responses.AccountResponse; +import org.stellar.sdk.responses.GsonSingleton; + +import java.math.BigInteger; + +public class XlmData extends CoinData { + private CoinEngine.InternalAmount balance = null; + private AccountResponse accountResponse = null; + + + @Override + public void clearInfo() { + super.clearInfo(); + balance = null; + } + + public CoinEngine.InternalAmount getBalanceInInternalUnits() { + return balance; + + } + + public void setBalanceInInternalUnits(CoinEngine.InternalAmount value) { + balance = value; + } + + public AccountResponse getAccountResponse() { + return accountResponse; + } + + public void setAccountResponse(AccountResponse accountResponse) { + this.accountResponse = accountResponse; + } + + @Override + public void loadFromBundle(Bundle B) { + super.loadFromBundle(B); + + if (B.containsKey("BalanceCurrency") && B.containsKey("BalanceDecimal")) { + String currency = B.getString("BalanceCurrency"); + balance = new CoinEngine.InternalAmount(B.getString("BalanceDecimal"), currency); + } else { + balance = null; + } + + if (B.containsKey("accountResponse")) { + accountResponse = GsonSingleton.getInstance().fromJson(B.getString("accountResponse"), AccountResponse.class); + } else { + accountResponse = null; + } + + } + + @Override + public void saveToBundle(Bundle B) { + super.saveToBundle(B); + try { + if (balance != null) { + B.putString("BalanceCurrency", balance.getCurrency()); + B.putString("BalanceDecimal", balance.toString()); + } + + if (accountResponse != null) { + B.putString("accountResponse", GsonSingleton.getInstance().toJson(accountResponse)); + } + + } catch (Exception e) { + Log.e("Can't save to bundle ", e.getMessage()); + } + + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/tangem/domain/wallet/xlm/XlmEngine.java b/app/src/main/java/com/tangem/domain/wallet/xlm/XlmEngine.java new file mode 100644 index 0000000000..406a7e1804 --- /dev/null +++ b/app/src/main/java/com/tangem/domain/wallet/xlm/XlmEngine.java @@ -0,0 +1,509 @@ +package com.tangem.domain.wallet.xlm; + +import android.net.Uri; +import android.text.InputFilter; +import android.util.Log; + +import com.tangem.data.Blockchain; +import com.tangem.data.network.ServerApiStellar; +import com.tangem.data.network.StellarRequest; +import com.tangem.domain.wallet.BalanceValidator; +import com.tangem.domain.wallet.CoinData; +import com.tangem.domain.wallet.CoinEngine; +import com.tangem.domain.wallet.TangemContext; +import com.tangem.tangemcard.data.TangemCard; +import com.tangem.tangemcard.tasks.SignTask; +import com.tangem.tangemcard.util.Util; +import com.tangem.util.DecimalDigitsInputFilter; +import com.tangem.wallet.R; + +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.Memo; +import org.stellar.sdk.PaymentOperation; +import org.stellar.sdk.Transaction; +import org.stellar.sdk.responses.AccountResponse; +import org.stellar.sdk.xdr.TransactionEnvelope; +import org.stellar.sdk.xdr.XdrDataInputStream; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.math.BigDecimal; + +public class XlmEngine extends CoinEngine { + + private static final String TAG = XlmEngine.class.getSimpleName(); + + public XlmData coinData = null; + + public XlmEngine(TangemContext context) throws Exception { + super(context); + if (context.getCoinData() == null) { + coinData = new XlmData(); + context.setCoinData(coinData); + } else if (context.getCoinData() instanceof XlmData) { + coinData = (XlmData) context.getCoinData(); + } else { + throw new Exception("Invalid type of Blockchain data for XlmEngine"); + } + } + + public XlmEngine() { + 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; + //TODO + return false;//coinData.getBalanceUnconfirmed() != 0; + } + + @Override + public String getBalanceHTML() { + Amount balance = getBalance(); + if (balance != null) { + return balance.toDescriptionString(getDecimals()); + } else { + return ""; + } + } + + @Override + public String getBalanceCurrency() { + return "XLM"; + } + + @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.getBalanceInInternalUnits() != null; + } + + + @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 { + return true; + } + return false; + } + + @Override + public String getFeeCurrency() { + return "XLM"; + } + + @Override + public boolean validateAddress(String address) { + try { + KeyPair kp = KeyPair.fromAccountId(address); + // TODO is it possible to check address testNet or not +// if (ctx.getBlockchain() == Blockchain.StellarTestNet) { +// return false; +// } + } catch (Exception e) { + return false; + } + return true; + } + + + @Override + public boolean isNeedCheckNode() { + return false; + } + + @Override + public Uri getShareWalletUriExplorer() { + //TODO - ? + return Uri.parse((ctx.getBlockchain() == Blockchain.Bitcoin ? "https://blockchain.info/address/" : "https://testnet.blockchain.info/address/") + ctx.getCoinData().getWallet()); + } + + @Override + public Uri getShareWalletUri() { + //TODO - ? + if (ctx.getCard().getDenomination() != null) { + return Uri.parse("bitcoin:" + ctx.getCoinData().getWallet() + "?amount=" + convertToAmount(convertToInternalAmount(ctx.getCard().getDenomination())).toValueString(8)); + } else { + return Uri.parse("bitcoin:" + 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) { + try { + 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; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + @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) { + KeyPair kp = KeyPair.fromPublicKey(pkUncompressed); + return kp.getAccountId(); + } + + private static BigDecimal multiplier = new BigDecimal("1000000"); + + @Override + public Amount convertToAmount(InternalAmount internalAmount) { + BigDecimal d = internalAmount.divide(multiplier); + 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(multiplier); + return new InternalAmount(d, "stroops"); + } + + @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), "stroops"); + } + + @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 XlmData(); + } + + @Override + public String getUnspentInputsDescription() { + return ""; + } + + @Override + public SignTask.PaymentToSign constructPayment(Amount amountValue, Amount feeValue, boolean IncFee, String targetAddress) throws Exception { + checkBlockchainDataExists(); + + Transaction transaction = new Transaction.Builder(coinData.getAccountResponse()) + .addOperation(new PaymentOperation.Builder(KeyPair.fromAccountId(targetAddress), new AssetTypeNative(), amountValue.toValueString()).build()) + // A memo allows you to add your own metadata to a transaction. It's + // optional and does not affect how Stellar treats the transaction. + .addMemo(Memo.text("TangemCard Transaction")) + .build(); + + if( transaction.getFee()!=convertToInternalAmount(feeValue).intValueExact() ) + { + throw new Exception("Invalid fee!"); + } + + 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[1][]; + dataForSign[0] = transaction.hash(); + return dataForSign; + } + + @Override + public byte[] getRawDataToSign() throws Exception { + throw new Exception("Hashes length must be identical!"); + } + + @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 { + // Sign the transaction to prove you are actually the person sending it. + transaction.sign(signFromCard); + + byte[] txForSend = transaction.toEnvelopeXdrBase64().getBytes(); + notifyOnNeedSendPayment(txForSend); + return txForSend; + } + }; + } + + @Override + public void requestBalanceAndUnspentTransactions(BlockchainRequestsCallbacks blockchainRequestsCallbacks) { + final ServerApiStellar serverApi = new ServerApiStellar(); + + ServerApiStellar.Listener listener = new ServerApiStellar.Listener() { + @Override + public void onSuccess(StellarRequest.Base request) { + Log.i(TAG, "onSuccess: " + request.getClass().getSimpleName()); + if (!StellarRequest.Balance.class.isInstance(request)) { + ctx.setError("Invalid request logic"); + blockchainRequestsCallbacks.onComplete(false); + return; + } + StellarRequest.Balance balanceRequest = (StellarRequest.Balance) request; + + coinData.setAccountResponse(balanceRequest.accountResponse); + AccountResponse.Balance balance=balanceRequest.accountResponse.getBalances()[0]; + coinData.setBalanceInInternalUnits(new InternalAmount(balance.getBalance(), "stroops")); + if (serverApi.isRequestsSequenceCompleted()) { + blockchainRequestsCallbacks.onComplete(!ctx.hasError()); + } else { + blockchainRequestsCallbacks.onProgress(); + } + } + + + @Override + public void onFail(StellarRequest.Base request) { + Log.i(TAG, "onFail: " + request.getClass().getSimpleName() + " " + request.getError()); + ctx.setError(request.getError()); + if (serverApi.isRequestsSequenceCompleted()) { + blockchainRequestsCallbacks.onComplete(false); + } else { + blockchainRequestsCallbacks.onProgress(); + } + } + }; + + serverApi.setListener(listener); + + serverApi.requestData(ctx, new StellarRequest.Balance(coinData.getWallet())); + } + + @Override + public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) throws Exception { + final int calcSize = 0; + Log.e(TAG, String.format("Estimated tx size %d", calcSize)); + coinData.minFee = null; + coinData.maxFee = null; + coinData.normalFee = null; + coinData.minFee = new Amount("0.00001", getFeeCurrency()); + coinData.normalFee = new Amount("0.00001", getFeeCurrency()); + coinData.maxFee = new Amount("0.00001", getFeeCurrency()); + blockchainRequestsCallbacks.onComplete(true); + } + + @Override + public void requestSendTransaction(BlockchainRequestsCallbacks blockchainRequestsCallbacks, byte[] txForSend) throws IOException { + final ServerApiStellar serverApi = new ServerApiStellar(); + + ServerApiStellar.Listener listener = new ServerApiStellar.Listener() { + @Override + public void onSuccess(StellarRequest.Base request) { + try { + if (!StellarRequest.SubmitTransaction.class.isInstance(request)) throw new Exception("Invalid request logic"); + StellarRequest.SubmitTransaction submitTransactionRequest = (StellarRequest.SubmitTransaction) request; + if (submitTransactionRequest.response.isSuccess()) { + ctx.setError(null); + blockchainRequestsCallbacks.onComplete(true); + } else { + ctx.setError("Rejected by node"); + blockchainRequestsCallbacks.onComplete(false); + } + } catch (Exception e) { + if (e.getMessage() != null) { + ctx.setError(e.getMessage()); + blockchainRequestsCallbacks.onComplete(false); + } else { + ctx.setError(e.getClass().getName()); + blockchainRequestsCallbacks.onComplete(false); + } + } + + } + + @Override + public void onFail(StellarRequest.Base request) { + ctx.setError(request.getError()); + blockchainRequestsCallbacks.onComplete(false); + } + }; + serverApi.setListener(listener); + + TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(txForSend))); + org.stellar.sdk.Transaction transaction = org.stellar.sdk.Transaction.fromEnvelopeXdr(transactionEnvelope); + serverApi.requestData(ctx, new StellarRequest.SubmitTransaction(transaction)); + + } + +} \ No newline at end of file diff --git a/tangemcard-android/src/main/res/drawable/ic_logo_stellar.png b/tangemcard-android/src/main/res/drawable/ic_logo_stellar.png new file mode 100644 index 0000000000..b8fbbd75b4 Binary files /dev/null and b/tangemcard-android/src/main/res/drawable/ic_logo_stellar.png differ