Updated on 2026-08-14

This commit is contained in:
Tangem 2019-02-15 19:26:53 +03:00
parent 803f9a76af
commit 102131b70c
14 changed files with 3091 additions and 4 deletions

View file

@ -51,6 +51,7 @@ dependencies {
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
implementation 'androidx.biometric:biometric:1.0.0-alpha03'
implementation 'co.nstant.in:cbor:0.8'
implementation 'com.google.android.material:material:1.1.0-alpha02'
implementation 'com.google.dagger:dagger:2.21'
kapt 'com.google.dagger:dagger-compiler:2.21'
@ -62,6 +63,7 @@ dependencies {
implementation 'com.scottyab:rootbeer-lib:0.0.7'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.skyfishjy.ripplebackground:library:1.0.1'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

View file

@ -16,7 +16,8 @@ public enum Blockchain {
BitcoinCash("BCH", "BCH", 100000000.0, R.drawable.ic_logo_bitcoin_cash, "Bitcoin Cash"),
Litecoin("LTC", "LTC", 100000000.0, R.drawable.ic_logo_bitcoin, "Litecoin"),
Rootstock("RSK", "RBTC", 1.0, R.drawable.ic_logo_bitcoin, "Rootstock"),
RootstockToken("Token", "RBTC", 1.0, R.drawable.ic_logo_bat_token, "Rootstock");
RootstockToken("Token", "RBTC", 1.0, R.drawable.ic_logo_bat_token, "Rootstock"),
Cardano("CARDANO", "ADA", 1000000.0,R.drawable.ic_logo_bitcoin, "Cardano");
Blockchain(String ID, String currency, double multiplier, int imageResource, String officialName) {
mID = ID;

View file

@ -0,0 +1,29 @@
package com.tangem.data.network;
import com.tangem.data.network.model.AdaliteResponse;
import com.tangem.data.network.model.AdaliteResponseUtxo;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface AdaliteApi {
@GET(ServerApiAdalite.ADALITE_ADDRESS)
Call<AdaliteResponse> adaliteAddress(@Path("address") String address);
@Headers("Content-Type: application/json")
@POST(ServerApiAdalite.ADALITE_UNSPENT_OUTPUTS)
Call<AdaliteResponseUtxo> adaliteUnspent(@Body String address);
// @GET(ServerApiAdalite.ADALITE_TRANSACTION)
// Call<AdaliteResponse> adaliteTransaction(@Path("txId") String txId);
@Headers("Content-Type: application/json")
@POST(ServerApiAdalite.ADALITE_SEND)
Call<AdaliteResponse> adaliteSend(@Body String rawTx );
}

View file

@ -0,0 +1,123 @@
package com.tangem.data.network;
import android.util.Log;
import com.tangem.data.network.model.AdaliteResponse;
import com.tangem.data.network.model.AdaliteResponseUtxo;
import androidx.annotation.NonNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class ServerApiAdalite {
private static String TAG = ServerApiAdalite.class.getSimpleName();
public static final String ADALITE_ADDRESS = "/api/addresses/summary/{address}";
public static final String ADALITE_UNSPENT_OUTPUTS = "/api/bulk/addresses/utxo";
// public static final String ADALITE_TRANSACTION = "/api/txs/raw/{txId}}";
public static final String ADALITE_SEND = "/tx/send";
private int requestsCount = 0;
public static String lastNode;
public boolean isRequestsSequenceCompleted() {
Log.i(TAG, String.format("isRequestsSequenceCompleted: %s (%d requests left)", String.valueOf(requestsCount <= 0), requestsCount));
return requestsCount <= 0;
}
private ResponseListener responseListener;
public interface ResponseListener {
void onSuccess(String method, AdaliteResponse adaliteResponse);
void onSuccess(String method, AdaliteResponseUtxo adaliteResponseUtxo);
void onFail(String method, String message);
}
public void setResponseListener(ResponseListener listener) {
responseListener = listener;
}
public void requestData(String method, String wallet, String tx) {
requestsCount++;
String adaliteURL = "https://explorer.adalite.io"; //TODO: make random selection
this.lastNode = adaliteURL; //TODO: show node instead of URL
Retrofit retrofitAdalite = new Retrofit.Builder()
.baseUrl(adaliteURL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
AdaliteApi adaliteApi = retrofitAdalite.create(AdaliteApi.class);
if (method.equals(ADALITE_UNSPENT_OUTPUTS)) {
Call<AdaliteResponseUtxo> call = adaliteApi.adaliteUnspent("[\"" + wallet + "\"]");
call.enqueue(new Callback<AdaliteResponseUtxo>() {
@Override
public void onResponse(@NonNull Call<AdaliteResponseUtxo> call, @NonNull Response<AdaliteResponseUtxo> response) {
if (response.code() == 200) {
requestsCount--;
responseListener.onSuccess(method, response.body());
Log.i(TAG, "requestData " + method + " onResponse " + response.code());
} else {
responseListener.onFail(method, String.valueOf(response.code()));
Log.e(TAG, "requestData " + method + " onResponse " + response.code());
}
}
@Override
public void onFailure(@NonNull Call<AdaliteResponseUtxo> call, @NonNull Throwable t) {
responseListener.onFail(method, String.valueOf(t.getMessage()));
Log.e(TAG, "requestData " + method + " onFailure " + t.getMessage());
}
});
} else {
Call<AdaliteResponse> call;
switch (method) {
case ADALITE_ADDRESS:
call = adaliteApi.adaliteAddress(wallet);
break;
// case ADALITE_TRANSACTION:
// call = adaliteApi.adaliteTransaction(tx);
// break;
case ADALITE_SEND:
call = adaliteApi.adaliteSend(tx);
break;
default:
call = adaliteApi.adaliteAddress(wallet);
break;
}
call.enqueue(new Callback<AdaliteResponse>() {
@Override
public void onResponse(@NonNull Call<AdaliteResponse> call, @NonNull Response<AdaliteResponse> response) {
if (response.code() == 200) {
requestsCount--;
responseListener.onSuccess(method, response.body());
Log.i(TAG, "requestData " + method + " onResponse " + response.code());
} else {
responseListener.onFail(method, String.valueOf(response.code()));
Log.e(TAG, "requestData " + method + " onResponse " + response.code());
}
}
@Override
public void onFailure(@NonNull Call<AdaliteResponse> call, @NonNull Throwable t) {
responseListener.onFail(method, String.valueOf(t.getMessage()));
Log.e(TAG, "requestData " + method + " onFailure " + t.getMessage());
}
});
}
}
}

View file

@ -0,0 +1,37 @@
package com.tangem.data.network.model
import com.google.gson.annotations.SerializedName
data class AdaliteResponse(
@SerializedName("Right")
var right: AddressData? = null
)
data class AdaliteResponseUtxo(
@SerializedName("Right")
var right: List<UtxoData>
)
data class AddressData(
@SerializedName("caAddress")
var caAddress: String? = null,
@SerializedName("caBalance")
var caBalance: AdaliteCoins? = null
)
data class AdaliteCoins(
@SerializedName("getCoin")
var getCoin: Long? = null
)
data class UtxoData(
@SerializedName("cuId")
var cuId: String? = null,
@SerializedName("cuOutIndex")
var cuOutIndex: Int? = null,
@SerializedName("cuCoins")
var cuCoins: AdaliteCoins? = null
)

View file

@ -15,6 +15,8 @@ import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import co.nstant.in.cbor.CborException;
/**
* Created by Ilia on 15.02.2018.
*/
@ -214,7 +216,7 @@ public abstract class CoinEngine {
public abstract boolean validateAddress(String address);
public abstract String calculateAddress(byte[] pkUncompressed) throws NoSuchProviderException, NoSuchAlgorithmException;
public abstract String calculateAddress(byte[] pkUncompressed) throws NoSuchProviderException, NoSuchAlgorithmException, CborException;
public abstract Amount convertToAmount(InternalAmount internalAmount) throws Exception;

View file

@ -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.cardano.CardanoEngine
import com.tangem.domain.wallet.ltc.LtcEngine
import com.tangem.domain.wallet.nftToken.NftTokenEngine
import com.tangem.domain.wallet.rsk.RskEngine
@ -33,6 +34,7 @@ object CoinEngineFactory {
Blockchain.Litecoin -> LtcEngine()
Blockchain.Rootstock -> RskEngine()
Blockchain.RootstockToken -> RskTokenEngine()
Blockchain.Cardano -> CardanoEngine()
else -> null
}
}
@ -57,6 +59,8 @@ object CoinEngineFactory {
RskEngine(context)
else if (Blockchain.RootstockToken == context.blockchain)
RskTokenEngine(context)
else if (Blockchain.Cardano == context.blockchain)
CardanoEngine(context)
else
return null
} catch (e: Exception) {

View file

@ -195,7 +195,6 @@ public class BtcEngine extends CoinEngine {
@Override
public Uri getShareWalletUri() {
byte[] x = new byte[] {0,0,0,0,0,0,0,0};
if (ctx.getCard().getDenomination() != null && !ctx.getCard().getDenominationText().equals("0.00")) {
return Uri.parse("bitcoin:" + ctx.getCoinData().getWallet() + "?amount=" + convertToAmount(convertToInternalAmount(ctx.getCard().getDenomination())).toValueString(8));
} else {

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,122 @@
package com.tangem.domain.wallet.cardano;
import android.os.Bundle;
import android.util.Log;
import com.tangem.domain.wallet.CoinData;
import com.tangem.domain.wallet.CoinEngine;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class CardanoData extends CoinData {
public CardanoData() {
super();
}
private Long balance;
public String getUnspentInputsDescription() {
try {
// int gatheredUnspents = 0;
if( unspentOutputs ==null ) return "";
// for (int i = 0; i < unspentOutputs.size(); i++) {
// if (unspentOutputs.get(i).Raw != null && unspentOutputs.get(i).Raw.length() > 1) gatheredUnspents++;
// }
return String.valueOf(unspentOutputs.size()) + " unspents";// (" + String.valueOf(gatheredUnspents) + " received)";
}
catch (Exception e)
{
e.printStackTrace();
return "";
}
}
public static class UnspentOutput {
public String txID;
public Long Amount;
public Integer Index;
public Bundle getAsBundle() {
Bundle B = new Bundle();
B.putString("txID", txID);
B.putLong("Amount", Amount);
B.putInt("Index", Index);
return B;
}
public void loadFromBundle(Bundle B) {
txID = B.getString("txID");
Amount = B.getLong("Amount");
Index = B.getInt("Index");
}
}
private List<UnspentOutput> unspentOutputs = null;
public List<UnspentOutput> getUnspentOutputs() {
if (unspentOutputs == null) unspentOutputs = new ArrayList<>();
return unspentOutputs;
}
@Override
public void loadFromBundle(Bundle B) {
super.loadFromBundle(B);
if (B.containsKey("Balance")) balance = B.getLong("Balance");
else balance = null;
if (B.containsKey("UnspentTransactions")) {
unspentOutputs = new ArrayList<>();
Bundle BB = B.getBundle("UnspentTransactions");
Integer i = 0;
while (BB.containsKey(i.toString())) {
UnspentOutput t = new UnspentOutput();
t.loadFromBundle(BB.getBundle(i.toString()));
unspentOutputs.add(t);
i++;
}
}
}
@Override
public void saveToBundle(Bundle B) {
super.saveToBundle(B);
try {
if (unspentOutputs != null) {
Bundle BB = new Bundle();
for (Integer i = 0; i < unspentOutputs.size(); i++) {
BB.putBundle(i.toString(), unspentOutputs.get(i).getAsBundle());
}
B.putBundle("UnspentTransactions", BB);
}
if (balance != null) B.putLong("Balance", balance);
} catch (Exception e) {
Log.e("Can't save to bundle ", e.getMessage());
}
}
@Override
public void clearInfo() {
super.clearInfo();
balance = null;
unspentOutputs = null;
}
public CoinEngine.InternalAmount getBalanceInInternalUnits() {
return new CoinEngine.InternalAmount(BigDecimal.valueOf(balance),"Lovelace");
}
public void setBalance(Long balance) {
this.balance = balance;
}
public Long getBalance() {
return balance;
}
public boolean hasBalanceInfo() {
return balance != null;
}
}

View file

@ -0,0 +1,665 @@
package com.tangem.domain.wallet.cardano;
import android.net.Uri;
import android.text.InputFilter;
import android.util.Log;
import com.tangem.data.network.ServerApiAdalite;
import com.tangem.data.network.model.AdaliteResponse;
import com.tangem.data.network.model.AdaliteResponseUtxo;
import com.tangem.data.network.model.UtxoData;
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.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.DecimalDigitsInputFilter;
import com.tangem.wallet.R;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.zip.CRC32;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.builder.ArrayBuilder;
import co.nstant.in.cbor.model.DataItem;
import static com.tangem.domain.wallet.Base58.decodeBase58;
import static com.tangem.domain.wallet.Base58.encodeBase58;
public class CardanoEngine extends CoinEngine {
private static final String TAG = CardanoEngine.class.getSimpleName();
private static final long protocolMagic = 764824073;
public CardanoData coinData = null;
public CardanoEngine(TangemContext context) throws Exception {
super(context);
if (context.getCoinData() == null) {
coinData = new CardanoData();
context.setCoinData(coinData);
} else if (context.getCoinData() instanceof CardanoData) {
coinData = (CardanoData) context.getCoinData();
} else {
throw new Exception("Invalid type of Blockchain data for CardanoEngine");
}
}
public CardanoEngine() {
super();
}
private static int getDecimals() {
return 6;
}
private void checkBlockchainDataExists() throws Exception {
if (coinData == null) throw new Exception("No blockchain data");
}
@Override
public boolean awaitingConfirmation() {
return false;
}
@Override
public String getBalanceHTML() {
Amount balance = getBalance();
if (balance != null) {
return balance.toDescriptionString(getDecimals());
} else {
return "";
}
}
@Override
public String getBalanceCurrency() {
return "ADA";
}
@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.getUnspentOutputs().size() == 0) {
ctx.setMessage(R.string.please_wait_for_confirmation);
} else {
return true;
}
return false;
}
@Override
public String getFeeCurrency() {
return "BTC";
}
@Override
public boolean validateAddress(String address) {
if (address == null || address.isEmpty()) {
return false;
}
byte[] decAddress = Base58.decodeBase58(address);
if (decAddress == null || decAddress.length == 0) {
return false;
}
ByteArrayInputStream bais = new ByteArrayInputStream(decAddress);
try {
List<DataItem> list = new CborDecoder(bais).decode();
// DataItem[] array = (DataItem[]) list.toArray(); TODO: Complete
// byte[] addressDataEncoded = (byte[]) array[0].getTag().getValue();
// int crc32Checksum = (int) array[1].getTag().getValue();
// CRC32 Checksum = new CRC32();
// Checksum.update();
// if (crc32Checksum !== CRC32(addressDataEncoded)) {
// return false
// }
} catch (CborException e) {
return false;
}
if (address.length() < 30) { //TODO: Check
return false;
}
return true;
}
@Override
public boolean isNeedCheckNode() {
return true;
}
@Override
public Uri getWalletExplorerUri() {
return Uri.parse("https://cardanoexplorer.com/address/" + ctx.getCoinData().getWallet());
}
@Override
public Uri getShareWalletUri() {
return Uri.parse(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;
}
if (coinData.isBalanceReceived()) {// && coinData.isBalanceEqual()) { TODO:check
balanceValidator.setScore(100);
balanceValidator.setFirstLine("Verified balance");
balanceValidator.setSecondLine("Balance confirmed in blockchain");
if (coinData.getBalanceInInternalUnits().isZero()) {
balanceValidator.setFirstLine("Empty wallet");
balanceValidator.setSecondLine("");
}
}
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. ");
}
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) throws CborException {
final Blake2b blake2b = Blake2b.Digest.newInstance(28);
byte[] pkHash = blake2b.digest(pkUncompressed);
//pkHash + attributes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addArray()
.add(pkHash)
.addMap()//additional attributes
.end()
.add(0)//address type
.end()
.build());
byte[] addr = baos.toByteArray();
final CRC32 crc32 = new CRC32();
crc32.update(addr);
int checksum = (int) crc32.getValue();
DataItem addrItem = new CborBuilder().add(addr).build().get(0);
addrItem.setTag(24);
//addr + checksum
baos.reset();
new CborEncoder(baos).encode(new CborBuilder()
.addArray()
.add(addrItem)
.add(checksum)
.end()
.build());
byte[] hexAddress = baos.toByteArray();
return encodeBase58(hexAddress);
}
@Override
public Amount convertToAmount(InternalAmount internalAmount) {
BigDecimal d = internalAmount.divide(new BigDecimal("1000000"));
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("1000000"));
return new InternalAmount(d, "Lovelace");
}
@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), "Lovelace");
}
@Override
public byte[] convertToByteArray(InternalAmount internalAmount) {
byte[] bytes = Util.longToByteArray(internalAmount.longValueExact());
// byte[] reversed = new byte[bytes.length]; TODO: check if needed
// for (int i = 0; i < bytes.length; i++) reversed[i] = bytes[bytes.length - i - 1];
// return reversed;
return bytes;
}
@Override
public CoinData createCoinData() {
return new CardanoData();
}
@Override
public String getUnspentInputsDescription() {
return coinData.getUnspentInputsDescription();
}
@Override
public SignTask.TransactionToSign constructTransaction(Amount amountValue, Amount feeValue, boolean IncFee, String targetAddress) throws Exception {
checkBlockchainDataExists();
String myAddress = ctx.getCoinData().getWallet();
byte[] pbKey = ctx.getCard().getWalletPublicKey();
List<CardanoData.UnspentOutput> utxoList = coinData.getUnspentOutputs();
long fullAmount = coinData.getBalance();
// long fullAmount = 0; TODO: check
// 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));
}
CborBuilder cborBuilder = new CborBuilder();
ArrayBuilder<CborBuilder> inputsArray = cborBuilder.startArray();
ArrayBuilder<CborBuilder> outputsArray = cborBuilder.startArray();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//Inputs
for (CardanoData.UnspentOutput utxo : utxoList) {
baos.reset();
//txID + inputPos
new CborEncoder(baos).encode(new CborBuilder()
.addArray()
.add(Util.fromHexString(utxo.txID))
.add(utxo.Index)
.end()
.build());
byte[] input = baos.toByteArray();
DataItem inputItem = new CborBuilder().add(input).build().get(0);
inputItem.setTag(24);
//input type + input
inputsArray
.addArray()
.add(0)
.add(inputItem)
.end();
}
//1st output
DataItem targetAddressItem = new CborDecoder(new ByteArrayInputStream(decodeBase58(targetAddress))).decode().get(0);
outputsArray
.addArray()
.add(targetAddressItem)
.add(amountFinal)
.end();
//2nd output (optional)
if (changeFinal > 0) {
DataItem myAddressItem = new CborDecoder(new ByteArrayInputStream(decodeBase58(myAddress))).decode().get(0);
outputsArray
.addArray()
.add(myAddressItem)
.add(changeFinal)
.end();
}
inputsArray.end();
outputsArray.end();
baos.reset();
new CborEncoder(baos).encode(cborBuilder.build());
byte[] txBody = baos.toByteArray();
final Blake2b blake2b = Blake2b.Digest.newInstance(28);
byte[] txHash = blake2b.digest(txBody);
baos.reset();
new CborEncoder(baos).encode(new CborBuilder().add(protocolMagic).build());
byte[] magic = baos.toByteArray();
//dataToSign prefix
baos.reset();
baos.write(new byte[] {(byte) 0x01});
baos.write(magic);
baos.write(new byte[]{(byte) 0x58, (byte) 0x20});
baos.write(txHash);
byte[] dataToSign = baos.toByteArray();
return new SignTask.TransactionToSign() {
@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] = dataToSign;
return dataForSign;
}
@Override
public byte[] getRawDataToSign() throws Exception {
throw new Exception("Signing Raw Data is not supported for Cardano");
}
@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 {
//pubkey + signature
baos.reset();
new CborEncoder(baos).encode(new CborBuilder()
.addArray()
.add(ctx.getCard().getCardPublicKey())
.add(signFromCard)
.end()
.build());
byte[] witnessBody = baos.toByteArray();
DataItem witnessBodyItem = new CborBuilder().add(witnessBody).build().get(0);
witnessBodyItem.setTag(24);
//witness type + witness body
baos.reset();
new CborEncoder(baos).encode(new CborBuilder()
.addArray()
.add(0)
.add(witnessBodyItem)
.end()
.build());
byte[] witness = baos.toByteArray();
baos.reset();
new CborEncoder(baos).encode(new CborBuilder()
.addArray()
.add(txBody)
.add(witness)
.end()
.build());
byte[] txForSend = baos.toByteArray();
return txForSend;
}
};
}
@Override
public void requestBalanceAndUnspentTransactions(BlockchainRequestsCallbacks blockchainRequestsCallbacks) {
final ServerApiAdalite serverApiAdalite = new ServerApiAdalite();
ServerApiAdalite.ResponseListener adaliteListener = new ServerApiAdalite.ResponseListener() {
@Override
public void onSuccess(String method, AdaliteResponse adaliteResponse) {
Log.i(TAG, "onSuccess: " + method);
try {
String walletAddress = adaliteResponse.getRight().getCaAddress();
if (!walletAddress.equals(coinData.getWallet())) {
// todo - check
throw new Exception("Invalid wallet address in answer!");
}
coinData.setBalanceReceived(true);
coinData.setBalance(adaliteResponse.getRight().getCaBalance().getGetCoin());
coinData.setValidationNodeDescription(ServerApiAdalite.lastNode);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "FAIL INSIGHT_ADDRESS Exception");
}
if (serverApiAdalite.isRequestsSequenceCompleted()) {
blockchainRequestsCallbacks.onComplete(!ctx.hasError());
} else {
blockchainRequestsCallbacks.onProgress();
}
}
@Override
public void onSuccess(String method, AdaliteResponseUtxo adaliteResponseUtxo) {
Log.i(TAG, "onSuccess: " + method);
try {
coinData.getUnspentOutputs().clear();
for (UtxoData utxo : adaliteResponseUtxo.getRight()) {
CardanoData.UnspentOutput unspentOutput = new CardanoData.UnspentOutput();
unspentOutput.txID = utxo.getCuId();
unspentOutput.Amount = utxo.getCuCoins().getGetCoin();
unspentOutput.Index = utxo.getCuOutIndex();
coinData.getUnspentOutputs().add(unspentOutput);
}
} catch (Exception e) {
e.printStackTrace();
}
if (serverApiAdalite.isRequestsSequenceCompleted()) {
blockchainRequestsCallbacks.onComplete(!ctx.hasError());
} else {
blockchainRequestsCallbacks.onProgress();
Log.e(TAG, "FAIL INSIGHT_UNSPENT_OUTPUTS Exception");
}
}
@Override
public void onFail(String method, String message) {
Log.i(TAG, "onFail: " + method + " " + message);
ctx.setError(message);
if (serverApiAdalite.isRequestsSequenceCompleted()) {
blockchainRequestsCallbacks.onComplete(false);
} else {
blockchainRequestsCallbacks.onProgress();
}
}
};
serverApiAdalite.setResponseListener(adaliteListener);
serverApiAdalite.requestData(ServerApiAdalite.ADALITE_ADDRESS, ctx.getCoinData().getWallet(), "");
serverApiAdalite.requestData(ServerApiAdalite.ADALITE_UNSPENT_OUTPUTS, ctx.getCoinData().getWallet(), "");
}
@Override
public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) {
coinData.minFee = new Amount(new BigDecimal(0.2).setScale(6, RoundingMode.DOWN), ctx.getBlockchain().getCurrency());
coinData.normalFee = new Amount(new BigDecimal(0.2).setScale(6, RoundingMode.DOWN), ctx.getBlockchain().getCurrency());
coinData.maxFee = new Amount(new BigDecimal(0.2).setScale(6, RoundingMode.DOWN), ctx.getBlockchain().getCurrency());
blockchainRequestsCallbacks.onComplete(true);
}
@Override
public void requestSendTransaction(BlockchainRequestsCallbacks blockchainRequestsCallbacks, byte[] txForSend) {
final ServerApiAdalite serverApiAdalite = new ServerApiAdalite();
final String txStr = BTCUtils.toHex(txForSend);
final ServerApiAdalite.ResponseListener responseListener = new ServerApiAdalite.ResponseListener() {
@Override
public void onSuccess(String method, AdaliteResponse adaliteResponse) {
if (method.equals(ServerApiAdalite.ADALITE_SEND)) {
String resultString = adaliteResponse.toString();
try {
if (resultString.isEmpty()) {
ctx.setError("No response from node");
blockchainRequestsCallbacks.onComplete(false);
} else { // TODO: Make check for a valid send response
ctx.setError(null);
blockchainRequestsCallbacks.onComplete(true);
}
} catch (Exception e) {
if (e.getMessage() != null) {
ctx.setError(e.getMessage());
blockchainRequestsCallbacks.onComplete(false);
} else {
ctx.setError(e.getClass().getName());
blockchainRequestsCallbacks.onComplete(false);
Log.e(TAG, resultString);
}
}
}
}
@Override
public void onSuccess(String method, AdaliteResponseUtxo adaliteResponseUtxo) {
Log.e(TAG, "Wrong response type for ADALITE_SEND");
ctx.setError("Wrong response type for ADALITE_SEND");
}
@Override
public void onFail(String method, String message) {
if (!serverApiAdalite.isRequestsSequenceCompleted()) {
ctx.setError(message);
blockchainRequestsCallbacks.onComplete(false);
}
}
};
serverApiAdalite.setResponseListener(responseListener);
serverApiAdalite.requestData(ServerApiAdalite.ADALITE_SEND, "", txStr);
}
}

View file

@ -0,0 +1,4 @@
package com.tangem.domain.wallet.cardano;
public final class CardanoUtils {
}

View file

@ -253,7 +253,7 @@ public class DucatusEngine extends BtcEngine {
return false;
}
if (coinData.isBalanceReceived() && coinData.isBalanceEqual()) {
if (coinData.isBalanceReceived()) {// && coinData.isBalanceEqual()) { TODO:check
balanceValidator.setScore(100);
balanceValidator.setFirstLine("Verified balance");
balanceValidator.setSecondLine("Balance confirmed in blockchain");

View file

@ -734,6 +734,7 @@ class LoadedWallet : androidx.fragment.app.Fragment(), NfcAdapter.ReaderCallback
Blockchain.Litecoin -> "litecoin"
Blockchain.Rootstock -> "bitcoin"
Blockchain.RootstockToken -> "bitcoin"
Blockchain.Cardano -> "cardano" //TODO:check
else -> {
throw Exception("Can''t get rate for blockchain " + ctx.blockchainName)
}