From 07bc724ecdbdc74f7074354795687f325a1fea8a Mon Sep 17 00:00:00 2001 From: Tangem Date: Fri, 11 Jan 2019 09:13:19 +0300 Subject: [PATCH 1/6] Updated on 2026-08-14 --- app/build.gradle | 8 +- .../main/java/com/tangem/data/Blockchain.java | 31 +- .../tangem/data/network/ServerApiStellar.java | 151 ++++++ .../com/tangem/data/network/ServerURL.java | 1 + .../tangem/data/network/StellarRequest.java | 72 +++ .../tangem/domain/wallet/CoinEngineFactory.kt | 3 + .../com/tangem/domain/wallet/xlm/XlmData.java | 81 +++ .../tangem/domain/wallet/xlm/XlmEngine.java | 509 ++++++++++++++++++ .../src/main/res/drawable/ic_logo_stellar.png | Bin 0 -> 23528 bytes 9 files changed, 839 insertions(+), 17 deletions(-) create mode 100644 app/src/main/java/com/tangem/data/network/ServerApiStellar.java create mode 100644 app/src/main/java/com/tangem/data/network/StellarRequest.java create mode 100644 app/src/main/java/com/tangem/domain/wallet/xlm/XlmData.java create mode 100644 app/src/main/java/com/tangem/domain/wallet/xlm/XlmEngine.java create mode 100644 tangemcard-android/src/main/res/drawable/ic_logo_stellar.png 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 0000000000000000000000000000000000000000..b8fbbd75b4937406888bee3e6161cb66e5c2ab46 GIT binary patch literal 23528 zcmeHvby$?!_wP$6-3=l`8pP1TNDP89(jpClLw9$FAkrX`5)vXvDAEmzfPjRAbc={| ziPU{Z&+<=gafG_x|p4|6!hIm|1)6wf25LEB0FZd4>l{3ep6)w738O5ZpvaDTAL4 zs5kam@UQZyB^LOBV~fyq002BP)Ef;*dQ1%fxbkL_l1fUZHjXw9rZ%>ao05_cTYDR0 zGfN`?a2-y$?V|B;hf-`}$B0Pn+Q-$G@s@r76LUUxE3sw++4jKUx@Fc71;pjfNeh)3u(*L zQ9zXvn>qlA1}2$E=kd^@lz~<*l~!_~l^S?)`;{Rs5DNg7Zl2eefII@=>*h_dGr-5( zhoe-$$Bc8i*g!ZMka$s=1sz@u+*S2c=0I;~0@Cy0Ok9`^g=oH-WxUepzO`on=Ln4` zBKTdvH}M)r2LKU52PDsvbz(r|Fw(hu>nC&dYy&G0Xh1{zqt1BQUOw`QN8Pk8>#LK~ zjMGh)FRvk~E)g5!%rZTWPi7`V%wx#C#|Hq~-JZrnA@QjBPqR~>jOQ&^Hk&gJEmm!q z#2D8m4r{{DF#%$Qu9acExw!!h+ZMDJPW2YK+Q6_HU^=mThi?QYT?@C{eK*uiXdiw) z^@&oe2>m%+JiH}V{U^2DGofNfd{Z`)q2Ajd_i)606|hT!Cl)kh1{~NSt(^;%Bj(#N zukl##%rhUh1o|9ATl$yly)H@UVV263&hWbjD}R06@)W zYMp1XRB~^z0YEC<@A3-?Ec{0D{073ujr27QROraFQgD2h1`*uS;Xa{`lb}&) zfPKU)eStxnPLec5T++xRL@+-|s^hn4OLg`xb!roJO%M*IL@PEKk`We6q95^*={+`8 zVgx1=62Twin*~`2Ccnkh+-jeNo_oza`VNA5oztFNI9vz*J!+&C!W*(5QX|b1>sNdW zqYvE)UiplHHso!(Lysdr(H-Bo42vGxlJlazWf?g=vY(wC0k4n<1K%DVLgTO@q)yoV z>vtb$(6Y5q8q8@3s6`4G&}&?Arl4y`MXq48pojXBeZ|(jN8DuT9~C97A*UhvjP)yX z327C!I!?eno~8>-51%QPu)34(zH!xuy^PYhk$}?JTigVzb9`Y>QD=ZR4}p#lHEF_~`N|qA10fy|&l0<>avD;AuIW z3>M|ASW+1QBk?)R>@?nMiRpQ_I&)L|u=9dpX<9d}(w&u{x9{hY@jE54b|zCwwr6o> z_ID?lnV9XELKhsXaK-}8UytvO@3r`hwJ^UBu<3$N5JV8rg3!N6V?pCVlS5rj15K2B zdgeoXVyg=GATM2_Ndi%VjjG1w?aQ7N(eFqf!5*nS@_sa*r=sehD&Fswho|yfmFT&y zn%C1Cs;`u0a&h`7pZDj|t5)X<7QR<@QI1sVx}}#{r+480-GHDtDDXyl5F%5>p!_XO zI3wj-UZXXQYXkOb7>gVh3G({d#k*hSoX_mhIYT|f7->qH}b`*Lzs zc<8ard&c(!?>#s%IK??%4wx4h7kC$38FnA88`fX4U!q)E9A0sgU^`AY zRf1KwssgJl}gMw-{zctKL5DUsD%hp-;8%8 z>rGbkY~7{KSc@d%s-BV$jvXDX9HaRk^V_~g2=_m>NJZ8S)r{)9pYZR9rVw$*kQeaAUc`hlyCS3T_=ojRN?ZEF^@rubjy zzR7*Ppl(8E^28x!LxAe3Y*agGymLI&ZL6G+9P2dq_D6HH%T>LlAGR`+tCL3yhOGL= zIz*ejp6|(XCDXOtc`dpkvAMdVF>Ti|laiC1)3gya57l+n)zsaqJ+JucFZ?_jkTY;clCSwLFBjkDYtdX zHH9;G(Hha_&}#i?{a#^MU@%}NVrF9roC!ZueHMx@MsW=vhd`6T{-I3+)jHj-0pF+z zM^X>PJM0t+ExPaA9c*&v2S_4C*eOh?mp6Vi^DWDnUDHNDM8ec3v z7XZ1Y1f^D-%dwWHCtJUl9H@A`E+ahS*30q=8IhPzDQb_lg~qOWNq#pCQoP~xmJdf! zncXd#CZ>{kLtag4U_8HT$Zm*JIQDVu<4k1&v$zuWLGJR4<%-7a><aSN*GKb!#a^d2+qg-X^YPQD(z7CuL(XC*W4_{80OE26Wc^Ia!~08(H{ zyQ3_BWc`U?=C*r^&z*L)gM#Pfbwg~!1NCDr9vg%K^b}XeS7N``l(M_3Thw0n+OqCl z_8*I+)u*ef|KvSZA?>2roEqto?SZv@ePz+y(Z+JLsJ^}!$4Xf+{5%3?JD2QhGn~AX z*mOpakrYKnrmXkX%}+m76RqQ#wCcWO-} zyHdre9GB(F^>*4e#^)pNtk&3WGVSP(u$Idfh!%=Ud)ppNA&RtZ7L9h=m()cH9XI6{ zulB5b@cC}u(C;w#ZIJ6unp^G4+pl!x)@)$!~WX?smP_Bw8WFxu1F%d-UP{RIhZ0bU*VA=J3cA1_n9;+S+x) z_YbFXigU=i-g&DXxh*<8pPx9G-jnUp*#EeSw;S43U+9**VZZV`w+Pn4+`>@v-c5Av z>3+fc5wDesm8yxBT86}n`|v}hjh^oYEjitaJ7V*mhx^c-dmDSKy=i;^0An#z(Qwp| zmxCGDSaBf@ZS;+}T&--uG86zr#9eKX1{Ow+5Pc&PGiy<%mFjvXh?$`%le&OBx4f;S zk*OKN-QMW7yMl^=yM=+UA(OZmu81oPRA6P~h=jOWSz0^5Tt%6F=!JpbQNvIs$d4(G z7NSfNs0AS!@=6d%8+#*&0GA-A0S})L`BypHKTH2#;(uH6 z7yCah4BA9q{@;cF+^?0@zb@_Ic-e^#?1wA-w2%n+tT0J?Bc!8^y^4*ErPxm|`>T5b znO2*UXJU_9LH+-cTvaUEd%7$O~!|CN^C=l-V0&;Vv^ zV{e6Y6f?6znixTCtxZIre+~XN^Osk_ByB8h?7?jriSda*|84kRrNAy#>1UHF=AbNn z4RZ6kq#%#5pdcqN7til%ew+83o*y0yyJ_vLt;nWx6=I1mP;zk-7T`?38GB)^O40-wA#s8sN%ErJ66?K28HbklBHZT%0 zzJla5(&yFZ6cFUs=M>`8H|FHl7ce%^=j9dV75Jt4H}QX{RiX3`;pshk@gNosK^y%`ZIKYCBt924khy= z1Hh05sH`YvfC?-lLlNlTM*rH@FUdc|%>KoI{}swV_5UXRpVx3PHL^Y_Fn_B0G3!4o zaj-FVbV1r1Ntl2>@!#Z(pIZMec3iy(6m^PNn*Bd8gagv~|I!TqRUG}Fn&Dq^+y6f^ z{N=?4rbufOBSSIhpAP)zz<+1CpZ5HFWc`_I{uzlPsACNVMltA7$RE)I=DmN6{k8JX z`5LHbv~>D0{|YZR_=57F{{A8QJNvk(=EJ%3@~5GGE9ZVh z;LlO8SOn`-=&wTcAHn%6hy71}`RkGXC$%2ab-KtgKu#u4;W`h?kQZy06CdFh3jN|j&V=nItIwelh#> zlc#WtuY6aZlko2FS_eDO@MxbBucm*D*j&CQsoy8J}a^Q@D-+ zax!@e*U9)Cg5w81SgNzuL@l?Tld9&;%Qsb(b609z z6Vj|K=Do&O+;B@E`?5jj*ewc7b6o8FM3i!d%A;bs(^BUo~7N;!Tx+*%wLYL-; zi+AwYyF6xzLBfd0VF>|9$ufB)Smb;7y`uau*N($7-kuS1h_YEsvUa&>s%Ijr~6y2!l)OJ0JDjH`j9N%vG;IPDm z6qn?sLaSF}XDA0UTU%*d;G2W?+#`2J)@I$QNP#DKnQ7pZoii;=VONQZ3|Ey`Y|5$| z3?1O{yJ88JgfCv4xBZ6oq}&IAxiCmg7$_YD1V3#{o>FpsW9aZTVX1IQ=7!>Cb^k)( z_#xwGyog5Ii};Fc#*n0szMG9Cv+u7C0j!Z`|?hIP*>a6Lh$>YANvsKBVo$IY}W z4IV{~`c+>gV_WpThb;L-_FG2-rMsx@YEV; za))Vz{Sq zd91HPffF;Bqj25tMgKxT-J}L4j<1sCKIH(0S0hgyPJwDzTI(x~%biqjLe}NgC3#I< zVed8(;c1A}gC@;(8gYs5lL!?O=WkekGZlm^Kt{&b#0Skz^s|=}DA{7g> zvD+J~?d z|0>g1f#K;S2(GGAm#zu^cYtYHV|_akv`rO)8=022k&!CjMG_Nkef5ik79y|2&$C`% zc;b>a%euPe^N22EVTr-Nv^I>5MX0VK$W%X|=nT1D4J!)}SkP(TT=-D-nfd#&c2B*x zpS=uk_OF8gkb-%Om@AKUPc*ckzxWN$&^cmF9o0L8(Ukxr+9p3F^6gM}ex!Qr)`RTc z5CX0^nfTG#A*yqs7l+_(=p^yT40^Z_KtjD7~Mm8`=FRoI!``q^-9@yp$3A3!Xb(Y=M(CB)q z1=A|T=`wV4;NzrI{k{kWNK)qYS*x9sDFdJMoS~|iSd3^ zG-H$1L#~H*YgEEHbU+4ZbC-#l-TH-@0m?>YB#YeyIc}pjZ;KCojId3XD1X)955#ijO zJyWJnu=G4{n!O{*6Q7oDLR7Ox7!rbEJ|iiNn3c+m5(}HU9^+KoEc0==Cs_5y0<_3(JcuC z`iWec?7!xF(3Ds>?-vcwl1H|3b!ml4XW??l1qi|%m}2b>6>pUqayc=;ZFc;7d{xI+ zm1HNi&Egf9)gRcN8)W2|PF&&wjnhARmXm(GXJr2V4IPt7_OIJ4enqs&hR6#a5jpZeRP zQ|hux$VvvN0IUyYQ`^%Z zc!tl%axP(I94ykGQ;)e79Rsg8pFKPX*;?-(0}q1PZ8U3W+IIf+?@?;jPcp$|eY5r* zgCrRQEQT1sVngg5rBj%0$c@pjtax^F2&K{8#IL*)T@gV!XO*FPV~>ori|Jl?%cj0b#!2FnvKFi|xE_cFYu537Lko>|uoT^+{y!C~DXs7k+#{Zy^5 zsea}%L>IQN+rhGgGD8#)PBS|mXRcKMryLPnymv|1g@e(w}VBo_xmL#d~XV1z~Z!J{LQli@NXfw+yt;GjV1WB7CV)1)6#lo(Rd>oa% zgs4&~PUf{WSJAt~EHIPQnRD(t*n<_{*7AXN(hoDmc%jiFw(+Nt04eu8D5$*KUT@ZXM8t0H~yfB=XKwI`_GI>8A3fOY8@) zhC^-6AWA|wOS9IlD6b<@oyOdbjQt*4#L)U=R;lH(!0q(pi)r2}DhIlEAG*7mRd`OR z4M?{ei{{}(fhnA7PnEQj+dF3W$=GVU>eB)R8)X}el^_VvVn^Sk8qf)D(s_;!jpg9- zVESOlTGn!SnjO}(Rw<9l?ae$BiTqn&R$#5Zy;bt{9WiFBA#Ymi9bU_`Xkbe3^YAI2 zllUZMQT)h%JPzV}-Y}B3pz((PsBJ{xmSve%_XsH_Sf$1%U-IZn2;ogyUcrmFnY=&> z)?-6otoW<;f|62}qIC@3G?csMDx2=RkF9pEV_vjYR}dWe*49ViezXG~o2?X>+8JFr z+1T8)skGgpYY!~q$VM136Ln#8Z%-^A^H!!+MNbklcGeF`;&8~PaB&yU}JH3u>rEMh! z&*loVqSbfK9=%$dG1{%N>jwoo3)j(Oqhxy3bl=j0HIuy2q%5x(FLc^DbD0!^Mq59~ zkmYe;)^`Y=4`5whRmvN9b|xndXif@vHYc&v`Mw}_E!wz)Bj4l|g~whrfIAmyo2n5m z`?)~uBa@Xw_Xd|Di!bczJ*nZe0bQR;)lm29nNZB`^e-Hhjj}2G!j<>5u{aRP81ipH zV3)UZ9soJ&wu_$8Bp#kofDtb|W<)h$sg=ms)VuO}-Ni0kjU-O3 z?!i8veKH0q+>bnl=9}*YGQOY~DSH}*DMB9>ARFa!L|+85nljte!xMBr>6m&njD_T}v`LzQkjb`s&vle0jBBet4dD-|o45 z6;$Z#OO+}kT@3ww!lU%w1L>PuVApe4Bz|*s)dy_xsdOqBWScPno zA+dgcVT<|Y8d;6^=-K3>4`;ZJe46SHS|o=SL%;^$;d6HLQPM)A=jRJ9-MSopRG#Mj z*>$hq#7%exia+7kG)wRLY8>bO+Qb@51!t(|K6bXQZh-xQ0;`9TSt43`Do`&%M;k4} zz&LK{)RerX;JR_=0=$YqEk~}n2<#V^B-CH;l%%t7|IktT+z9>60M6YO|wVk~Z)(OkY^Lr=x+5>~uUjH85Zb1kioo!zT$ zF_smGmYR`B&Sxopab65=tx^?B?NcDzFl$I`b)6?K>}asF`*qCtQG4&W9yX%9af0$t zgBQ*=A6w#0(8_&v=xGimnyKu4<@gQg;z2o#ofN(-5Y_%H%A1L^N*1hj{o1KQ#!|#6 zi2T1b1TPXr11w9s6(!p~8`mn=Hog^-ksj?qSBvySE?;_}pIeg0Lj3fqMd!Cz540%Y zthI|$>~1a^2v=h!np&CvXy=RlkJ+>_h-InVcNd;8A%Kt&-8o+I{<^czZ?nCCc@NA^XH9f$=#y5}G8UaBNPQ%PFsa|Yr7u?}<^oOx|N zz1Xco#nPUm@)!L$fjL(&u0+=AwNiE=s`%q%Bsm^|%>u@(HMME)CQ-yon0U()c7)nAv9!Eyae9#0kMZq=iEo)Gm-y&gOKEcaD(Gdgy@nCa)_n>`-AE zq76D2RaJ-cpff1X6rTuoGFr-fVqk3nf2~S=8Qb>dp3jl4+My{8MlAPXQ@qRMR;J*$ zr5pxW*2D_f)uw_ih$VQLLY!b3kz#)~5j@!@z=ps)y1~-L>VqKV&He@tNo=L}-x$gp zq3nk?efz?~5sMY`>lgYUK)CjF7`xA9ntDpJ?tvJBv|aL(9W&n>F}J)3q*@uwpx= z#T``@F_bn!yMk!h*o7h%?~eKjsrg0&{Uq>@v ze_T7#IihCFZ%%xhFStnie2v@A3t#NS?$J2N_6O<@HYKIyd0T7kq1Ib>g0wSB_Kkb4o+-h6{CTF^3J_b=W0^Ppo48 zFw*4$soa)t6QJF-%C7WPgglN z3HC)FGg0 zU39*$T)D@9<2%XTRHExIjjlup7U!rCN!XS`SCU8HclhHX5go@DUV@9p?ckRl2YmSO zA!1>{3@ZkZphp`R96aI{7G6kAO?95c3QP|Hzzag+8R?bC^a!BGw2v3$J$2JY^H)aa z;NaMlQ&6b7aN)w(H#Ej)Oz;(3&zON|F+4mx(Ql2AXH39T z5t6%XMo)gUV@K?c==qpG#;}xf&LnG5b!2bJw^=Nauh%#&T)?s z8!qAwYE=2|^I*+Dk+_K)6H-;L%>A4negmTQV>a&>b6p(F3|8!P{sdN037MZnRGXpL zE!ZTlsOS=WA%L444e{=kGDZAnZ#g$6d`TetPAa&@B(X@766Q1GhCl>E{x%c71n^|J zh`fVzMj8~sM+@G}o$YC3_q(Kc4~Y%;ACd{TW|@1?uZyC-yTpF>{< Date: Sun, 13 Jan 2019 15:11:29 +0300 Subject: [PATCH 2/6] Updated on 2026-08-14 --- app/build.gradle | 4 +- .../main/java/com/tangem/data/Blockchain.java | 2 +- .../tangem/data/network/ServerApiStellar.java | 74 ++-- .../tangem/data/network/StellarRequest.java | 18 +- .../tangem/domain/wallet/CoinEngineFactory.kt | 1 + .../com/tangem/domain/wallet/xlm/XlmData.java | 57 ++- .../tangem/domain/wallet/xlm/XlmEngine.java | 87 ++-- .../activity/ConfirmPaymentActivity.kt | 4 +- .../activity/SendTransactionActivity.kt | 2 +- .../presentation/fragment/LoadedWallet.kt | 5 +- .../main/java/org/stellar/sdk/Account.java | 45 +++ .../java/org/stellar/sdk/AccountFlag.java | 32 ++ .../stellar/sdk/AccountMergeOperation.java | 80 ++++ .../org/stellar/sdk/AllowTrustOperation.java | 133 ++++++ app/src/main/java/org/stellar/sdk/Asset.java | 72 ++++ .../sdk/AssetCodeLengthInvalidException.java | 16 + .../stellar/sdk/AssetTypeCreditAlphaNum.java | 52 +++ .../sdk/AssetTypeCreditAlphaNum12.java | 41 ++ .../stellar/sdk/AssetTypeCreditAlphaNum4.java | 41 ++ .../java/org/stellar/sdk/AssetTypeNative.java | 34 ++ .../stellar/sdk/BumpSequenceOperation.java | 79 ++++ .../org/stellar/sdk/ChangeTrustOperation.java | 98 +++++ .../stellar/sdk/CreateAccountOperation.java | 105 +++++ .../sdk/CreatePassiveOfferOperation.java | 136 +++++++ .../java/org/stellar/sdk/FormatException.java | 15 + .../org/stellar/sdk/InflationOperation.java | 16 + .../main/java/org/stellar/sdk/KeyPair.java | 262 ++++++++++++ .../org/stellar/sdk/ManageDataOperation.java | 107 +++++ .../org/stellar/sdk/ManageOfferOperation.java | 165 ++++++++ app/src/main/java/org/stellar/sdk/Memo.java | 93 +++++ .../main/java/org/stellar/sdk/MemoHash.java | 28 ++ .../org/stellar/sdk/MemoHashAbstract.java | 69 ++++ app/src/main/java/org/stellar/sdk/MemoId.java | 40 ++ .../main/java/org/stellar/sdk/MemoNone.java | 22 + .../java/org/stellar/sdk/MemoReturnHash.java | 29 ++ .../main/java/org/stellar/sdk/MemoText.java | 44 ++ .../org/stellar/sdk/MemoTooLongException.java | 15 + .../main/java/org/stellar/sdk/Network.java | 71 ++++ .../sdk/NoNetworkSelectedException.java | 10 + .../sdk/NotEnoughSignaturesException.java | 14 + .../main/java/org/stellar/sdk/Operation.java | 134 ++++++ .../org/stellar/sdk/PathPaymentOperation.java | 192 +++++++++ .../org/stellar/sdk/PaymentOperation.java | 123 ++++++ app/src/main/java/org/stellar/sdk/Price.java | 110 +++++ app/src/main/java/org/stellar/sdk/SLIP10.java | 65 +++ app/src/main/java/org/stellar/sdk/Server.java | 203 ++++++++++ .../org/stellar/sdk/SetOptionsOperation.java | 343 ++++++++++++++++ app/src/main/java/org/stellar/sdk/Signer.java | 83 ++++ app/src/main/java/org/stellar/sdk/StrKey.java | 157 ++++++++ .../main/java/org/stellar/sdk/TimeBounds.java | 66 +++ .../java/org/stellar/sdk/Transaction.java | 381 ++++++++++++++++++ .../sdk/TransactionBuilderAccount.java | 26 ++ .../java/org/stellar/sdk/TransactionEx.java | 75 ++++ app/src/main/java/org/stellar/sdk/Util.java | 73 ++++ .../sdk/requests/AccountsRequestBuilder.java | 107 +++++ .../sdk/requests/AssetsRequestBuilder.java | 41 ++ .../sdk/requests/EffectsRequestBuilder.java | 124 ++++++ .../stellar/sdk/requests/ErrorResponse.java | 23 ++ .../stellar/sdk/requests/EventListener.java | 12 + .../sdk/requests/LedgersRequestBuilder.java | 106 +++++ .../sdk/requests/OffersRequestBuilder.java | 81 ++++ .../OperationFeeStatsRequestBuilder.java | 32 ++ .../requests/OperationsRequestBuilder.java | 140 +++++++ .../sdk/requests/OrderBookRequestBuilder.java | 79 ++++ .../sdk/requests/PathsRequestBuilder.java | 71 ++++ .../sdk/requests/PaymentsRequestBuilder.java | 114 ++++++ .../stellar/sdk/requests/RequestBuilder.java | 97 +++++ .../stellar/sdk/requests/ResponseHandler.java | 54 +++ .../org/stellar/sdk/requests/SSEStream.java | 195 +++++++++ .../requests/TooManyRequestsException.java | 21 + .../TradeAggregationsRequestBuilder.java | 61 +++ .../sdk/requests/TradesRequestBuilder.java | 101 +++++ .../requests/TransactionsRequestBuilder.java | 129 ++++++ .../sdk/responses/AccountResponse.java | 351 ++++++++++++++++ .../sdk/responses/AssetDeserializer.java | 26 ++ .../stellar/sdk/responses/AssetResponse.java | 109 +++++ .../sdk/responses/EffectDeserializer.java | 83 ++++ .../stellar/sdk/responses/GsonSingleton.java | 51 +++ .../sdk/responses/KeyPairTypeAdapter.java | 21 + .../stellar/sdk/responses/LedgerResponse.java | 171 ++++++++ .../java/org/stellar/sdk/responses/Link.java | 39 ++ .../stellar/sdk/responses/OfferResponse.java | 97 +++++ .../sdk/responses/OperationDeserializer.java | 53 +++ .../responses/OperationFeeStatsResponse.java | 37 ++ .../sdk/responses/OrderBookResponse.java | 77 ++++ .../java/org/stellar/sdk/responses/Page.java | 93 +++++ .../sdk/responses/PageDeserializer.java | 51 +++ .../stellar/sdk/responses/PathResponse.java | 104 +++++ .../org/stellar/sdk/responses/Response.java | 53 +++ .../stellar/sdk/responses/RootResponse.java | 62 +++ .../responses/SubmitTransactionResponse.java | 182 +++++++++ ...itTransactionTimeoutResponseException.java | 8 + ...itTransactionUnknownResponseException.java | 24 ++ .../responses/TradeAggregationResponse.java | 78 ++++ .../stellar/sdk/responses/TradeResponse.java | 195 +++++++++ .../responses/TransactionDeserializer.java | 60 +++ .../sdk/responses/TransactionResponse.java | 179 ++++++++ .../stellar/sdk/responses/TypedResponse.java | 14 + .../effects/AccountCreatedEffectResponse.java | 22 + .../AccountCreditedEffectResponse.java | 45 +++ .../effects/AccountDebitedEffectResponse.java | 44 ++ .../AccountFlagsUpdatedEffectResponse.java | 29 ++ ...ccountHomeDomainUpdatedEffectResponse.java | 22 + ...ationDestinationUpdatedEffectResponse.java | 11 + .../effects/AccountRemovedEffectResponse.java | 9 + ...ccountThresholdsUpdatedEffectResponse.java | 36 ++ .../effects/DataCreatedEffectResponse.java | 11 + .../effects/DataRemovedEffectResponse.java | 11 + .../effects/DataUpdatedEffectResponse.java | 11 + .../sdk/responses/effects/EffectResponse.java | 111 +++++ .../effects/OfferCreatedEffectResponse.java | 11 + .../effects/OfferRemovedEffectResponse.java | 11 + .../effects/OfferUpdatedEffectResponse.java | 11 + .../effects/SequenceBumpedEffectResponse.java | 22 + .../effects/SignerCreatedEffectResponse.java | 13 + .../effects/SignerEffectResponse.java | 23 ++ .../effects/SignerRemovedEffectResponse.java | 10 + .../effects/SignerUpdatedEffectResponse.java | 13 + .../effects/TradeEffectResponse.java | 85 ++++ .../TrustlineAuthorizationResponse.java | 32 ++ .../TrustlineAuthorizedEffectResponse.java | 15 + .../effects/TrustlineCUDResponse.java | 38 ++ .../TrustlineCreatedEffectResponse.java | 13 + .../TrustlineDeauthorizedEffectResponse.java | 15 + .../TrustlineRemovedEffectResponse.java | 13 + .../TrustlineUpdatedEffectResponse.java | 13 + .../AccountMergeOperationResponse.java | 31 ++ .../AllowTrustOperationResponse.java | 58 +++ .../BumpSequenceOperationResponse.java | 22 + .../ChangeTrustOperationResponse.java | 58 +++ .../CreateAccountOperationResponse.java | 38 ++ .../CreatePassiveOfferOperationResponse.java | 80 ++++ .../InflationOperationResponse.java | 10 + .../ManageDataOperationResponse.java | 29 ++ .../ManageOfferOperationResponse.java | 80 ++++ .../operations/OperationResponse.java | 121 ++++++ .../PathPaymentOperationResponse.java | 85 ++++ .../operations/PaymentOperationResponse.java | 58 +++ .../SetOptionsOperationResponse.java | 95 +++++ .../org/stellar/sdk/xdr/AccountEntry.java | 263 ++++++++++++ .../org/stellar/sdk/xdr/AccountFlags.java | 55 +++ .../java/org/stellar/sdk/xdr/AccountID.java | 30 ++ .../stellar/sdk/xdr/AccountMergeResult.java | 59 +++ .../sdk/xdr/AccountMergeResultCode.java | 63 +++ .../org/stellar/sdk/xdr/AllowTrustOp.java | 123 ++++++ .../org/stellar/sdk/xdr/AllowTrustResult.java | 50 +++ .../stellar/sdk/xdr/AllowTrustResultCode.java | 60 +++ .../main/java/org/stellar/sdk/xdr/Asset.java | 149 +++++++ .../java/org/stellar/sdk/xdr/AssetType.java | 48 +++ .../main/java/org/stellar/sdk/xdr/Auth.java | 36 ++ .../java/org/stellar/sdk/xdr/AuthCert.java | 54 +++ .../stellar/sdk/xdr/AuthenticatedMessage.java | 96 +++++ .../java/org/stellar/sdk/xdr/BucketEntry.java | 69 ++++ .../org/stellar/sdk/xdr/BucketEntryType.java | 45 +++ .../org/stellar/sdk/xdr/BumpSequenceOp.java | 34 ++ .../stellar/sdk/xdr/BumpSequenceResult.java | 50 +++ .../sdk/xdr/BumpSequenceResultCode.java | 47 +++ .../org/stellar/sdk/xdr/ChangeTrustOp.java | 46 +++ .../stellar/sdk/xdr/ChangeTrustResult.java | 50 +++ .../sdk/xdr/ChangeTrustResultCode.java | 61 +++ .../org/stellar/sdk/xdr/ClaimOfferAtom.java | 89 ++++ .../org/stellar/sdk/xdr/CreateAccountOp.java | 44 ++ .../stellar/sdk/xdr/CreateAccountResult.java | 50 +++ .../sdk/xdr/CreateAccountResultCode.java | 58 +++ .../stellar/sdk/xdr/CreatePassiveOfferOp.java | 64 +++ .../org/stellar/sdk/xdr/CryptoKeyType.java | 48 +++ .../org/stellar/sdk/xdr/Curve25519Public.java | 37 ++ .../org/stellar/sdk/xdr/Curve25519Secret.java | 37 ++ .../java/org/stellar/sdk/xdr/DataEntry.java | 100 +++++ .../java/org/stellar/sdk/xdr/DataValue.java | 34 ++ .../stellar/sdk/xdr/DecoratedSignature.java | 44 ++ .../java/org/stellar/sdk/xdr/DontHave.java | 44 ++ .../org/stellar/sdk/xdr/EnvelopeType.java | 48 +++ .../main/java/org/stellar/sdk/xdr/Error.java | 44 ++ .../java/org/stellar/sdk/xdr/ErrorCode.java | 54 +++ .../main/java/org/stellar/sdk/xdr/Hash.java | 33 ++ .../main/java/org/stellar/sdk/xdr/Hello.java | 114 ++++++ .../org/stellar/sdk/xdr/HmacSha256Key.java | 37 ++ .../org/stellar/sdk/xdr/HmacSha256Mac.java | 37 ++ .../java/org/stellar/sdk/xdr/IPAddrType.java | 45 +++ .../org/stellar/sdk/xdr/InflationPayout.java | 44 ++ .../org/stellar/sdk/xdr/InflationResult.java | 67 +++ .../stellar/sdk/xdr/InflationResultCode.java | 47 +++ .../main/java/org/stellar/sdk/xdr/Int32.java | 30 ++ .../main/java/org/stellar/sdk/xdr/Int64.java | 30 ++ .../java/org/stellar/sdk/xdr/LedgerEntry.java | 178 ++++++++ .../stellar/sdk/xdr/LedgerEntryChange.java | 98 +++++ .../sdk/xdr/LedgerEntryChangeType.java | 51 +++ .../stellar/sdk/xdr/LedgerEntryChanges.java | 38 ++ .../org/stellar/sdk/xdr/LedgerEntryType.java | 51 +++ .../org/stellar/sdk/xdr/LedgerHeader.java | 229 +++++++++++ .../sdk/xdr/LedgerHeaderHistoryEntry.java | 90 +++++ .../java/org/stellar/sdk/xdr/LedgerKey.java | 220 ++++++++++ .../stellar/sdk/xdr/LedgerSCPMessages.java | 52 +++ .../org/stellar/sdk/xdr/LedgerUpgrade.java | 98 +++++ .../stellar/sdk/xdr/LedgerUpgradeType.java | 51 +++ .../java/org/stellar/sdk/xdr/Liabilities.java | 44 ++ .../org/stellar/sdk/xdr/ManageDataOp.java | 52 +++ .../org/stellar/sdk/xdr/ManageDataResult.java | 50 +++ .../stellar/sdk/xdr/ManageDataResultCode.java | 58 +++ .../stellar/sdk/xdr/ManageOfferEffect.java | 48 +++ .../org/stellar/sdk/xdr/ManageOfferOp.java | 76 ++++ .../stellar/sdk/xdr/ManageOfferResult.java | 59 +++ .../sdk/xdr/ManageOfferResultCode.java | 84 ++++ .../sdk/xdr/ManageOfferSuccessResult.java | 106 +++++ .../main/java/org/stellar/sdk/xdr/Memo.java | 104 +++++ .../java/org/stellar/sdk/xdr/MemoType.java | 54 +++ .../java/org/stellar/sdk/xdr/MessageType.java | 85 ++++ .../main/java/org/stellar/sdk/xdr/NodeID.java | 30 ++ .../java/org/stellar/sdk/xdr/OfferEntry.java | 146 +++++++ .../org/stellar/sdk/xdr/OfferEntryFlags.java | 43 ++ .../java/org/stellar/sdk/xdr/Operation.java | 255 ++++++++++++ .../org/stellar/sdk/xdr/OperationMeta.java | 34 ++ .../org/stellar/sdk/xdr/OperationResult.java | 267 ++++++++++++ .../stellar/sdk/xdr/OperationResultCode.java | 52 +++ .../org/stellar/sdk/xdr/OperationType.java | 75 ++++ .../org/stellar/sdk/xdr/PathPaymentOp.java | 96 +++++ .../stellar/sdk/xdr/PathPaymentResult.java | 115 ++++++ .../sdk/xdr/PathPaymentResultCode.java | 81 ++++ .../java/org/stellar/sdk/xdr/PaymentOp.java | 54 +++ .../org/stellar/sdk/xdr/PaymentResult.java | 50 +++ .../stellar/sdk/xdr/PaymentResultCode.java | 72 ++++ .../java/org/stellar/sdk/xdr/PeerAddress.java | 118 ++++++ .../main/java/org/stellar/sdk/xdr/Price.java | 44 ++ .../java/org/stellar/sdk/xdr/PublicKey.java | 53 +++ .../org/stellar/sdk/xdr/PublicKeyType.java | 42 ++ .../java/org/stellar/sdk/xdr/SCPBallot.java | 44 ++ .../java/org/stellar/sdk/xdr/SCPEnvelope.java | 44 ++ .../org/stellar/sdk/xdr/SCPHistoryEntry.java | 53 +++ .../stellar/sdk/xdr/SCPHistoryEntryV0.java | 52 +++ .../org/stellar/sdk/xdr/SCPNomination.java | 70 ++++ .../org/stellar/sdk/xdr/SCPQuorumSet.java | 70 ++++ .../org/stellar/sdk/xdr/SCPStatement.java | 335 +++++++++++++++ .../org/stellar/sdk/xdr/SCPStatementType.java | 51 +++ .../org/stellar/sdk/xdr/SequenceNumber.java | 30 ++ .../org/stellar/sdk/xdr/SetOptionsOp.java | 193 +++++++++ .../org/stellar/sdk/xdr/SetOptionsResult.java | 50 +++ .../stellar/sdk/xdr/SetOptionsResultCode.java | 71 ++++ .../java/org/stellar/sdk/xdr/Signature.java | 34 ++ .../org/stellar/sdk/xdr/SignatureHint.java | 33 ++ .../main/java/org/stellar/sdk/xdr/Signer.java | 44 ++ .../java/org/stellar/sdk/xdr/SignerKey.java | 85 ++++ .../org/stellar/sdk/xdr/SignerKeyType.java | 48 +++ .../stellar/sdk/xdr/SimplePaymentResult.java | 54 +++ .../org/stellar/sdk/xdr/StellarMessage.java | 236 +++++++++++ .../org/stellar/sdk/xdr/StellarValue.java | 114 ++++++ .../java/org/stellar/sdk/xdr/String32.java | 30 ++ .../java/org/stellar/sdk/xdr/String64.java | 30 ++ .../org/stellar/sdk/xdr/ThresholdIndexes.java | 51 +++ .../org/stellar/sdk/xdr/ThresholdIndices.java | 51 +++ .../java/org/stellar/sdk/xdr/Thresholds.java | 33 ++ .../java/org/stellar/sdk/xdr/TimeBounds.java | 44 ++ .../java/org/stellar/sdk/xdr/Transaction.java | 155 +++++++ .../stellar/sdk/xdr/TransactionEnvelope.java | 54 +++ .../sdk/xdr/TransactionHistoryEntry.java | 90 +++++ .../xdr/TransactionHistoryResultEntry.java | 90 +++++ .../org/stellar/sdk/xdr/TransactionMeta.java | 76 ++++ .../stellar/sdk/xdr/TransactionMetaV1.java | 52 +++ .../stellar/sdk/xdr/TransactionResult.java | 150 +++++++ .../sdk/xdr/TransactionResultCode.java | 78 ++++ .../sdk/xdr/TransactionResultPair.java | 44 ++ .../stellar/sdk/xdr/TransactionResultSet.java | 42 ++ .../org/stellar/sdk/xdr/TransactionSet.java | 52 +++ .../sdk/xdr/TransactionSignaturePayload.java | 88 ++++ .../org/stellar/sdk/xdr/TrustLineEntry.java | 203 ++++++++++ .../org/stellar/sdk/xdr/TrustLineFlags.java | 43 ++ .../java/org/stellar/sdk/xdr/Uint256.java | 33 ++ .../main/java/org/stellar/sdk/xdr/Uint32.java | 30 ++ .../main/java/org/stellar/sdk/xdr/Uint64.java | 30 ++ .../java/org/stellar/sdk/xdr/UpgradeType.java | 34 ++ .../main/java/org/stellar/sdk/xdr/Value.java | 34 ++ .../stellar/sdk/xdr/XdrDataInputStream.java | 129 ++++++ .../stellar/sdk/xdr/XdrDataOutputStream.java | 102 +++++ app/src/main/res/values/strings.xml | 2 +- tangemcard-common/build.gradle | 1 + .../tangem/tangemcard/reader/CardCrypto.java | 293 +++++++++----- .../tangemcard/reader/CardProtocol.java | 5 +- .../tangemcard/tasks/CustomReadCardTask.java | 27 +- 278 files changed, 19571 insertions(+), 206 deletions(-) create mode 100644 app/src/main/java/org/stellar/sdk/Account.java create mode 100644 app/src/main/java/org/stellar/sdk/AccountFlag.java create mode 100644 app/src/main/java/org/stellar/sdk/AccountMergeOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/AllowTrustOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/Asset.java create mode 100644 app/src/main/java/org/stellar/sdk/AssetCodeLengthInvalidException.java create mode 100644 app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum.java create mode 100644 app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum12.java create mode 100644 app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum4.java create mode 100644 app/src/main/java/org/stellar/sdk/AssetTypeNative.java create mode 100644 app/src/main/java/org/stellar/sdk/BumpSequenceOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/ChangeTrustOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/CreateAccountOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/CreatePassiveOfferOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/FormatException.java create mode 100644 app/src/main/java/org/stellar/sdk/InflationOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/KeyPair.java create mode 100644 app/src/main/java/org/stellar/sdk/ManageDataOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/ManageOfferOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/Memo.java create mode 100644 app/src/main/java/org/stellar/sdk/MemoHash.java create mode 100644 app/src/main/java/org/stellar/sdk/MemoHashAbstract.java create mode 100644 app/src/main/java/org/stellar/sdk/MemoId.java create mode 100644 app/src/main/java/org/stellar/sdk/MemoNone.java create mode 100644 app/src/main/java/org/stellar/sdk/MemoReturnHash.java create mode 100644 app/src/main/java/org/stellar/sdk/MemoText.java create mode 100644 app/src/main/java/org/stellar/sdk/MemoTooLongException.java create mode 100644 app/src/main/java/org/stellar/sdk/Network.java create mode 100644 app/src/main/java/org/stellar/sdk/NoNetworkSelectedException.java create mode 100644 app/src/main/java/org/stellar/sdk/NotEnoughSignaturesException.java create mode 100644 app/src/main/java/org/stellar/sdk/Operation.java create mode 100644 app/src/main/java/org/stellar/sdk/PathPaymentOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/PaymentOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/Price.java create mode 100644 app/src/main/java/org/stellar/sdk/SLIP10.java create mode 100644 app/src/main/java/org/stellar/sdk/Server.java create mode 100644 app/src/main/java/org/stellar/sdk/SetOptionsOperation.java create mode 100644 app/src/main/java/org/stellar/sdk/Signer.java create mode 100644 app/src/main/java/org/stellar/sdk/StrKey.java create mode 100644 app/src/main/java/org/stellar/sdk/TimeBounds.java create mode 100644 app/src/main/java/org/stellar/sdk/Transaction.java create mode 100644 app/src/main/java/org/stellar/sdk/TransactionBuilderAccount.java create mode 100644 app/src/main/java/org/stellar/sdk/TransactionEx.java create mode 100644 app/src/main/java/org/stellar/sdk/Util.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/AccountsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/AssetsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/EffectsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/ErrorResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/EventListener.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/LedgersRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/OffersRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/OperationFeeStatsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/OperationsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/OrderBookRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/PathsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/PaymentsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/RequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/ResponseHandler.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/SSEStream.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/TooManyRequestsException.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/TradeAggregationsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/TradesRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/requests/TransactionsRequestBuilder.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/AccountResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/AssetDeserializer.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/AssetResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/EffectDeserializer.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/GsonSingleton.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/KeyPairTypeAdapter.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/LedgerResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/Link.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/OfferResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/OperationDeserializer.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/OperationFeeStatsResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/OrderBookResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/Page.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/PageDeserializer.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/PathResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/Response.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/RootResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/SubmitTransactionResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/SubmitTransactionTimeoutResponseException.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/SubmitTransactionUnknownResponseException.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/TradeAggregationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/TradeResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/TransactionDeserializer.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/TransactionResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/TypedResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/AccountCreatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/AccountCreditedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/AccountDebitedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/AccountFlagsUpdatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/AccountHomeDomainUpdatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/AccountInflationDestinationUpdatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/AccountRemovedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/AccountThresholdsUpdatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/DataCreatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/DataRemovedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/DataUpdatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/EffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/OfferCreatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/OfferRemovedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/OfferUpdatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/SequenceBumpedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/SignerCreatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/SignerEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/SignerRemovedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/SignerUpdatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/TradeEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/TrustlineAuthorizationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/TrustlineAuthorizedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/TrustlineCUDResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/TrustlineCreatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/TrustlineDeauthorizedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/TrustlineRemovedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/effects/TrustlineUpdatedEffectResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/AccountMergeOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/AllowTrustOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/BumpSequenceOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/ChangeTrustOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/CreateAccountOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/CreatePassiveOfferOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/InflationOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/ManageDataOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/ManageOfferOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/OperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/PathPaymentOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/PaymentOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/responses/operations/SetOptionsOperationResponse.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AccountEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AccountFlags.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AccountID.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AccountMergeResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AccountMergeResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AllowTrustOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AllowTrustResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AllowTrustResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Asset.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AssetType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Auth.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AuthCert.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/AuthenticatedMessage.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/BucketEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/BucketEntryType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/BumpSequenceOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/BumpSequenceResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/BumpSequenceResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ChangeTrustOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ChangeTrustResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ChangeTrustResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ClaimOfferAtom.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/CreateAccountOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/CreateAccountResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/CreateAccountResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/CreatePassiveOfferOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/CryptoKeyType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Curve25519Public.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Curve25519Secret.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/DataEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/DataValue.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/DecoratedSignature.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/DontHave.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/EnvelopeType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Error.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ErrorCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Hash.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Hello.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/HmacSha256Key.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/HmacSha256Mac.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/IPAddrType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/InflationPayout.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/InflationResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/InflationResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Int32.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Int64.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChange.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChangeType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChanges.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerEntryType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerHeader.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerHeaderHistoryEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerKey.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerSCPMessages.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerUpgrade.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/LedgerUpgradeType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Liabilities.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ManageDataOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ManageDataResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ManageDataResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ManageOfferEffect.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ManageOfferOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ManageOfferResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ManageOfferResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ManageOfferSuccessResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Memo.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/MemoType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/MessageType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/NodeID.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/OfferEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/OfferEntryFlags.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Operation.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/OperationMeta.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/OperationResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/OperationResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/OperationType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PathPaymentOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PathPaymentResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PathPaymentResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PaymentOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PaymentResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PaymentResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PeerAddress.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Price.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PublicKey.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/PublicKeyType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SCPBallot.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SCPEnvelope.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SCPHistoryEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SCPHistoryEntryV0.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SCPNomination.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SCPQuorumSet.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SCPStatement.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SCPStatementType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SequenceNumber.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SetOptionsOp.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SetOptionsResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SetOptionsResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Signature.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SignatureHint.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Signer.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SignerKey.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SignerKeyType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/SimplePaymentResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/StellarMessage.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/StellarValue.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/String32.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/String64.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ThresholdIndexes.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/ThresholdIndices.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Thresholds.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TimeBounds.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Transaction.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionEnvelope.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionHistoryEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionHistoryResultEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionMeta.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionMetaV1.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionResult.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionResultCode.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionResultPair.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionResultSet.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionSet.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TransactionSignaturePayload.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TrustLineEntry.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/TrustLineFlags.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Uint256.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Uint32.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Uint64.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/UpgradeType.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/Value.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/XdrDataInputStream.java create mode 100644 app/src/main/java/org/stellar/sdk/xdr/XdrDataOutputStream.java diff --git a/app/build.gradle b/app/build.gradle index d3fe8f8d93..d9ecb6da48 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -66,6 +66,7 @@ dependencies { implementation 'com.squareup.retrofit2:converter-gson:2.5.0' implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0' + implementation "com.squareup.okhttp3:okhttp-sse:3.11.0" implementation 'com.skyfishjy.ripplebackground:library:1.0.1' implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0' annotationProcessor 'com.google.dagger:dagger-compiler:2.16' @@ -78,5 +79,6 @@ 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' +// implementation 'com.github.stellar:java-stellar-sdk:0.4.1' + implementation 'net.i2p.crypto:eddsa:0.3.0' } \ 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 cc5828ecda..bccaaa60c5 100644 --- a/app/src/main/java/com/tangem/data/Blockchain.java +++ b/app/src/main/java/com/tangem/data/Blockchain.java @@ -15,7 +15,7 @@ public enum Blockchain { 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"); + StellarTestNet("XLM/test", "XLM", R.drawable.ic_logo_stellar, "Stellar Lumens"); Blockchain(String ID, String currency, int imageResource, String officialName) { mID = ID; mCurrency = currency; diff --git a/app/src/main/java/com/tangem/data/network/ServerApiStellar.java b/app/src/main/java/com/tangem/data/network/ServerApiStellar.java index dd95612984..2142d9ed8e 100644 --- a/app/src/main/java/com/tangem/data/network/ServerApiStellar.java +++ b/app/src/main/java/com/tangem/data/network/ServerApiStellar.java @@ -1,14 +1,14 @@ 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.util.LOG; import com.tangem.wallet.R; import org.stellar.sdk.Network; import org.stellar.sdk.Server; +import org.stellar.sdk.requests.ErrorResponse; import java.io.IOException; @@ -18,15 +18,17 @@ import io.reactivex.observers.DefaultObserver; import io.reactivex.schedulers.Schedulers; /** - * Request processor for Electrum Api + * Created by dvol on 7.01.2019. + * + * Request processor for Stellar Horizon Rest 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 + * {@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(); @@ -37,10 +39,10 @@ public class ServerApiStellar { */ private Listener listener; - private int requestsCount=0; + private int requestsCount = 0; public boolean isRequestsSequenceCompleted() { - Log.i(TAG, String.format("isRequestsSequenceCompleted: %s (%d requests left)", String.valueOf(requestsCount <= 0), requestsCount)); + LOG.i(TAG, String.format("isRequestsSequenceCompleted: %s (%d requests left)", String.valueOf(requestsCount <= 0), requestsCount)); return requestsCount <= 0; } @@ -51,11 +53,14 @@ public class ServerApiStellar { /** * 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); @@ -63,6 +68,7 @@ public class ServerApiStellar { /** * Set notificaion listener + * * @param listener */ public void setListener(Listener listener) { @@ -72,25 +78,26 @@ public class ServerApiStellar { /** * 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())); + LOG.i(TAG, String.format("New request[%d]: %s", requestsCount, stellarRequest.getClass().getSimpleName())); Observable stellarObserver = Observable.just(stellarRequest) - .doOnNext(stellarRequest1 -> doStellarRequest(ctx, stellarRequest)) + .doOnEach(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); -// }) -// + .flatMap(stellarRequest1 -> { + if (stellarRequest1.errorResponse != null) { + LOG.e(TAG, "Error response on " + stellarRequest.getClass().getSimpleName()); + return Observable.error(stellarRequest.errorResponse); + } else + return Observable.just(stellarRequest1); + } + ) .retryWhen(errors -> errors - .filter(throwable -> throwable instanceof IOException) + .filter(throwable -> (throwable instanceof IOException) || (throwable instanceof ErrorResponse)) .zipWith(Observable.range(1, 4), (n, i) -> i)) .subscribeOn(Schedulers.io()) @@ -99,14 +106,14 @@ public class ServerApiStellar { @Override public void onNext(StellarRequest.Base stellarRequest) { - + LOG.e(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onNext "); } @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)); + 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); @@ -118,12 +125,12 @@ public class ServerApiStellar { @Override public void onComplete() { requestsCount--; - Log.e(TAG, String.format("%d requests left in processing",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"); + LOG.i(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onComplete, error!=null"); listener.onFail(stellarRequest); } else { - Log.e(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onComplete, error==null"); + LOG.e(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onComplete, error==null"); listener.onSuccess(stellarRequest); } } @@ -134,14 +141,19 @@ public class ServerApiStellar { private void doStellarRequest(TangemContext ctx, StellarRequest.Base stellarRequest) throws IOException { stellarRequest.setError(null); try { - if( ctx.getBlockchain()==Blockchain.StellarTestNet ) { + if (ctx.getBlockchain() == Blockchain.StellarTestNet) { Network.useTestNetwork(); } Server server = new Server(ServerURL.API_STELLAR); - stellarRequest.process(server); - } - catch (Exception e) - { + try { + LOG.e(TAG, "--- request " + stellarRequest.getClass().getSimpleName()); + stellarRequest.process(server); + } catch (ErrorResponse errorResponse) { + LOG.e(TAG, "--- error response: " + errorResponse.getMessage()); + stellarRequest.errorResponse = errorResponse; + stellarRequest.setError(errorResponse.getMessage()); + } + } catch (Exception e) { e.printStackTrace(); stellarRequest.setError(App.getInstance().getString(R.string.cannot_obtain_data_from_blockchain_communication_error)); throw e; diff --git a/app/src/main/java/com/tangem/data/network/StellarRequest.java b/app/src/main/java/com/tangem/data/network/StellarRequest.java index 03a6fe90dc..88a50d8a6c 100644 --- a/app/src/main/java/com/tangem/data/network/StellarRequest.java +++ b/app/src/main/java/com/tangem/data/network/StellarRequest.java @@ -3,19 +3,22 @@ package com.tangem.data.network; import org.stellar.sdk.KeyPair; import org.stellar.sdk.Server; import org.stellar.sdk.Transaction; +import org.stellar.sdk.requests.ErrorResponse; import org.stellar.sdk.responses.AccountResponse; import org.stellar.sdk.responses.SubmitTransactionResponse; import java.io.IOException; /** - * Created by dvol on 16.07.2017. + * Created by dvol on 7.01.2019. */ public class StellarRequest { public static abstract class Base { + public ErrorResponse errorResponse; private String error = null; + public String getError() { return error; } @@ -28,28 +31,25 @@ public class StellarRequest { } public static class Balance extends Base { - public KeyPair accountKeyPair; + KeyPair accountKeyPair; public AccountResponse accountResponse; - public Balance(String walletAddress) - { - accountKeyPair=KeyPair.fromAccountId(walletAddress); + public Balance(String walletAddress) { + accountKeyPair = KeyPair.fromAccountId(walletAddress); } @Override public void process(Server server) throws IOException { - accountResponse=server.accounts().account(accountKeyPair); + 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; + this.transaction = transaction; } @Override 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 7685b20986..528c9d3147 100644 --- a/app/src/main/java/com/tangem/domain/wallet/CoinEngineFactory.kt +++ b/app/src/main/java/com/tangem/domain/wallet/CoinEngineFactory.kt @@ -28,6 +28,7 @@ object CoinEngineFactory { Blockchain.Ethereum, Blockchain.EthereumTestNet -> EthEngine() Blockchain.Token -> TokenEngine() Blockchain.Litecoin -> LtcEngine() + Blockchain.StellarTestNet, Blockchain.Stellar -> XlmEngine() else -> null } } 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 index a4ca60c528..32de8d2310 100644 --- a/app/src/main/java/com/tangem/domain/wallet/xlm/XlmData.java +++ b/app/src/main/java/com/tangem/domain/wallet/xlm/XlmData.java @@ -6,15 +6,26 @@ 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.KeyPair; import org.stellar.sdk.responses.AccountResponse; -import org.stellar.sdk.responses.GsonSingleton; -import java.math.BigInteger; +/* + * Created by dvol on 7.01.2019. + */ public class XlmData extends CoinData { - private CoinEngine.InternalAmount balance = null; - private AccountResponse accountResponse = null; + + + public static class AccountResponseEx extends AccountResponse + { + AccountResponseEx(String accountId, Long sequenceNumber) { + super(KeyPair.fromAccountId(accountId), sequenceNumber); + } + } + + private CoinEngine.Amount balance = null; + + private Long sequenceNumber = 0L; @Override @@ -23,21 +34,26 @@ public class XlmData extends CoinData { balance = null; } - public CoinEngine.InternalAmount getBalanceInInternalUnits() { + CoinEngine.Amount getBalanceXLM() { return balance; } - public void setBalanceInInternalUnits(CoinEngine.InternalAmount value) { - balance = value; + AccountResponse getAccountResponse() { + return new AccountResponseEx(getWallet(), sequenceNumber); } - public AccountResponse getAccountResponse() { - return accountResponse; + void setAccountResponse(AccountResponse accountResponse) { + if( accountResponse.getBalances().length>0 ) { + AccountResponse.Balance balanceResponse = accountResponse.getBalances()[0]; + balance = new CoinEngine.Amount(balanceResponse.getBalance(), "XLM"); + } + sequenceNumber = accountResponse.getSequenceNumber(); + setBalanceReceived(true); } - public void setAccountResponse(AccountResponse accountResponse) { - this.accountResponse = accountResponse; + public void incSequenceNumber() { + sequenceNumber++; } @Override @@ -46,17 +62,16 @@ public class XlmData extends CoinData { if (B.containsKey("BalanceCurrency") && B.containsKey("BalanceDecimal")) { String currency = B.getString("BalanceCurrency"); - balance = new CoinEngine.InternalAmount(B.getString("BalanceDecimal"), currency); + balance = new CoinEngine.Amount(B.getString("BalanceDecimal"), currency); } else { balance = null; } - if (B.containsKey("accountResponse")) { - accountResponse = GsonSingleton.getInstance().fromJson(B.getString("accountResponse"), AccountResponse.class); + if (B.containsKey("sequenceNumber")) { + sequenceNumber = B.getLong("sequenceNumber"); } else { - accountResponse = null; + sequenceNumber = 0L; } - } @Override @@ -65,11 +80,11 @@ public class XlmData extends CoinData { try { if (balance != null) { B.putString("BalanceCurrency", balance.getCurrency()); - B.putString("BalanceDecimal", balance.toString()); + B.putString("BalanceDecimal", balance.toValueString()); } - if (accountResponse != null) { - B.putString("accountResponse", GsonSingleton.getInstance().toJson(accountResponse)); + if (sequenceNumber != null) { + B.putLong("sequenceNumber", sequenceNumber); } } catch (Exception e) { @@ -77,5 +92,5 @@ public class XlmData extends CoinData { } } +} -} \ 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 index 406a7e1804..ceff856069 100644 --- a/app/src/main/java/com/tangem/domain/wallet/xlm/XlmEngine.java +++ b/app/src/main/java/com/tangem/domain/wallet/xlm/XlmEngine.java @@ -19,17 +19,19 @@ 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 org.stellar.sdk.TransactionEx; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigDecimal; +/** +* Created by dvol on 7.01.2019. +* +* PS. To create and fill testnet account just open https://friendbot.stellar.org/?addr=XXX in browser +**/ + public class XlmEngine extends CoinEngine { private static final String TAG = XlmEngine.class.getSimpleName(); @@ -53,6 +55,7 @@ public class XlmEngine extends CoinEngine { } private static int getDecimals() { + //TODO - Is it's right? return 8; } @@ -93,14 +96,14 @@ public class XlmEngine extends CoinEngine { @Override public boolean isBalanceNotZero() { if (coinData == null) return false; - if (coinData.getBalanceInInternalUnits() == null) return false; - return coinData.getBalanceInInternalUnits().notZero(); + if (coinData.getBalanceXLM() == null) return false; + return coinData.getBalanceXLM().notZero(); } @Override public boolean hasBalanceInfo() { if (coinData == null) return false; - return coinData.getBalanceInInternalUnits() != null; + return coinData.getBalanceXLM() != null; } @@ -145,17 +148,16 @@ public class XlmEngine extends CoinEngine { @Override public Uri getShareWalletUriExplorer() { - //TODO - ? - return Uri.parse((ctx.getBlockchain() == Blockchain.Bitcoin ? "https://blockchain.info/address/" : "https://testnet.blockchain.info/address/") + ctx.getCoinData().getWallet()); + return Uri.parse((ctx.getBlockchain() == Blockchain.Bitcoin ? "http://testnet.stellarchain.io/address/" : "http://testnet.stellarchain.io/address/") + ctx.getCoinData().getWallet()); } @Override public Uri getShareWalletUri() { - //TODO - ? + //TODO - how to construct payment query intent for stellar? if (ctx.getCard().getDenomination() != null) { - return Uri.parse("bitcoin:" + ctx.getCoinData().getWallet() + "?amount=" + convertToAmount(convertToInternalAmount(ctx.getCard().getDenomination())).toValueString(8)); + return Uri.parse("stellar:" + ctx.getCoinData().getWallet() + "?amount=" + convertToAmount(convertToInternalAmount(ctx.getCard().getDenomination())).toValueString()); } else { - return Uri.parse("bitcoin:" + ctx.getCoinData().getWallet()); + return Uri.parse("stellar:" + ctx.getCoinData().getWallet()); } } @@ -167,7 +169,7 @@ public class XlmEngine extends CoinEngine { @Override public boolean checkNewTransactionAmount(Amount amount) { if (coinData == null) return false; - if (amount.compareTo(convertToAmount(coinData.getBalanceInInternalUnits())) > 0) { + if (amount.compareTo(coinData.getBalanceXLM()) > 0) { return false; } return true; @@ -175,28 +177,23 @@ public class XlmEngine extends CoinEngine { @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) + if (feeValue == null || amountValue == null) return false; - if (fee.isZero() || amount.isZero()) + if (feeValue.isZero() || amountValue.isZero()) return false; - if (isIncludeFee && (amount.compareTo(coinData.getBalanceInInternalUnits()) > 0 || amount.compareTo(fee) < 0)) + if (isIncludeFee && (amountValue.compareTo(coinData.getBalanceXLM()) > 0 || amountValue.compareTo(feeValue) < 0)) return false; - if (!isIncludeFee && amount.add(fee).compareTo(coinData.getBalanceInInternalUnits()) > 0) + if (!isIncludeFee && amountValue.add(feeValue).compareTo(coinData.getBalanceXLM()) > 0) return false; return true; @@ -231,7 +228,7 @@ public class XlmEngine extends CoinEngine { balanceValidator.setScore(100); balanceValidator.setFirstLine("Verified balance"); balanceValidator.setSecondLine("Balance confirmed in blockchain"); - if (coinData.getBalanceInInternalUnits().isZero()) { + if (coinData.getBalanceXLM().isZero()) { balanceValidator.setFirstLine("Empty wallet"); balanceValidator.setSecondLine(""); } @@ -246,7 +243,7 @@ public class XlmEngine extends CoinEngine { // return; // } - if ((ctx.getCard().getOfflineBalance() != null) && !coinData.isBalanceReceived() && (ctx.getCard().getRemainingSignatures() == ctx.getCard().getMaxSignatures()) && coinData.getBalanceInInternalUnits().notZero()) { + if ((ctx.getCard().getOfflineBalance() != null) && !coinData.isBalanceReceived() && (ctx.getCard().getRemainingSignatures() == ctx.getCard().getMaxSignatures()) && coinData.getBalanceXLM().notZero()) { balanceValidator.setScore(80); balanceValidator.setFirstLine("Verified offline balance"); balanceValidator.setSecondLine("Can't obtain balance from blockchain. Restore internet connection to be more confident. "); @@ -277,7 +274,7 @@ public class XlmEngine extends CoinEngine { @Override public Amount getBalance() { if (!hasBalanceInfo()) return null; - return convertToAmount(coinData.getBalanceInInternalUnits()); + return coinData.getBalanceXLM(); } @Override @@ -305,7 +302,7 @@ public class XlmEngine extends CoinEngine { return kp.getAccountId(); } - private static BigDecimal multiplier = new BigDecimal("1000000"); + private static BigDecimal multiplier = new BigDecimal("10000000"); @Override public Amount convertToAmount(InternalAmount internalAmount) { @@ -350,16 +347,17 @@ public class XlmEngine extends CoinEngine { 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( IncFee ) + { + amountValue=new Amount(amountValue.subtract(feeValue), amountValue.getCurrency()); + } + + TransactionEx transaction = TransactionEx.buildEx(60, coinData.getAccountResponse(), new PaymentOperation.Builder(KeyPair.fromAccountId(targetAddress), new AssetTypeNative(), amountValue.toValueString()).build()); if( transaction.getFee()!=convertToInternalAmount(feeValue).intValueExact() ) { @@ -382,12 +380,12 @@ public class XlmEngine extends CoinEngine { @Override public byte[] getRawDataToSign() throws Exception { - throw new Exception("Hashes length must be identical!"); + return transaction.signatureBase(); } @Override public String getHashAlgToSign() { - return "sha-256x2"; + return "sha-256"; } @Override @@ -398,7 +396,7 @@ public class XlmEngine extends CoinEngine { @Override public byte[] onSignCompleted(byte[] signFromCard) throws Exception { // Sign the transaction to prove you are actually the person sending it. - transaction.sign(signFromCard); + transaction.setSign(signFromCard); byte[] txForSend = transaction.toEnvelopeXdrBase64().getBytes(); notifyOnNeedSendPayment(txForSend); @@ -423,8 +421,6 @@ public class XlmEngine extends CoinEngine { 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 { @@ -453,6 +449,7 @@ public class XlmEngine extends CoinEngine { @Override public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) throws Exception { final int calcSize = 0; + // todo - take BASE_FEE from last leger Log.e(TAG, String.format("Estimated tx size %d", calcSize)); coinData.minFee = null; coinData.maxFee = null; @@ -477,7 +474,15 @@ public class XlmEngine extends CoinEngine { ctx.setError(null); blockchainRequestsCallbacks.onComplete(true); } else { - ctx.setError("Rejected by node"); + if( submitTransactionRequest.response.getExtras()!=null && submitTransactionRequest.response.getExtras().getResultCodes()!=null ) { + String trResult = submitTransactionRequest.response.getExtras().getResultCodes().getTransactionResultCode(); + if( submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes()!=null && submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes().size()>0 ) { + trResult+="/"+submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes().get(0); + } + ctx.setError(trResult); + }else{ + ctx.setError("transaction failed"); + } blockchainRequestsCallbacks.onComplete(false); } } catch (Exception e) { @@ -500,8 +505,8 @@ public class XlmEngine extends CoinEngine { }; serverApi.setListener(listener); - TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(txForSend))); - org.stellar.sdk.Transaction transaction = org.stellar.sdk.Transaction.fromEnvelopeXdr(transactionEnvelope); + Transaction transaction = TransactionEx.fromEnvelopeXdr(new String(txForSend)); + coinData.incSequenceNumber(); serverApi.requestData(ctx, new StellarRequest.SubmitTransaction(transaction)); } diff --git a/app/src/main/java/com/tangem/presentation/activity/ConfirmPaymentActivity.kt b/app/src/main/java/com/tangem/presentation/activity/ConfirmPaymentActivity.kt index 5ab55e0c3c..58a99e652a 100644 --- a/app/src/main/java/com/tangem/presentation/activity/ConfirmPaymentActivity.kt +++ b/app/src/main/java/com/tangem/presentation/activity/ConfirmPaymentActivity.kt @@ -76,7 +76,9 @@ class ConfirmPaymentActivity : AppCompatActivity(), NfcAdapter.ReaderCallback { btnSend.visibility = View.INVISIBLE - rgFee.isEnabled = !(ctx.blockchain == Blockchain.Ethereum || ctx.blockchain == Blockchain.EthereumTestNet || ctx.blockchain == Blockchain.Token || ctx.blockchain == Blockchain.BitcoinCash || ctx.blockchain == Blockchain.Litecoin) + for (lol in rgFee.touchables) { + lol.isEnabled = !(ctx.blockchain == Blockchain.Ethereum || ctx.blockchain == Blockchain.EthereumTestNet || ctx.blockchain == Blockchain.Token || ctx.blockchain == Blockchain.BitcoinCash || ctx.blockchain == Blockchain.Litecoin || ctx.blockchain == Blockchain.Stellar || ctx.blockchain == Blockchain.StellarTestNet) + } // set listeners rgFee.setOnCheckedChangeListener { _, checkedId -> doSetFee(checkedId) } diff --git a/app/src/main/java/com/tangem/presentation/activity/SendTransactionActivity.kt b/app/src/main/java/com/tangem/presentation/activity/SendTransactionActivity.kt index 3152227a80..f1a72721ac 100644 --- a/app/src/main/java/com/tangem/presentation/activity/SendTransactionActivity.kt +++ b/app/src/main/java/com/tangem/presentation/activity/SendTransactionActivity.kt @@ -42,7 +42,7 @@ class SendTransactionActivity : AppCompatActivity(), NfcAdapter.ReaderCallback { if (success) finishWithSuccess() else - finishWithError(this@SendTransactionActivity.getString(R.string.try_again_failed_to_send_transaction)) + finishWithError(ctx.error) } override fun onProgress() { diff --git a/app/src/main/java/com/tangem/presentation/fragment/LoadedWallet.kt b/app/src/main/java/com/tangem/presentation/fragment/LoadedWallet.kt index ca23b0aa1d..fe06ec58f9 100644 --- a/app/src/main/java/com/tangem/presentation/fragment/LoadedWallet.kt +++ b/app/src/main/java/com/tangem/presentation/fragment/LoadedWallet.kt @@ -622,7 +622,8 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific // Litecoin // BitcoinCash if (ctx.blockchain == Blockchain.Bitcoin || ctx.blockchain == Blockchain.BitcoinTestNet || - ctx.blockchain == Blockchain.Litecoin || ctx.blockchain == Blockchain.BitcoinCash) { + ctx.blockchain == Blockchain.Litecoin || ctx.blockchain == Blockchain.BitcoinCash || + ctx.blockchain == Blockchain.Stellar || ctx.blockchain == Blockchain.StellarTestNet ) { ctx.coinData.setIsBalanceEqual(true) } @@ -705,6 +706,8 @@ class LoadedWallet : Fragment(), NfcAdapter.ReaderCallback, CardProtocol.Notific Blockchain.Token -> "ethereum" Blockchain.BitcoinCash -> "bitcoin-cash" Blockchain.Litecoin -> "litecoin" + Blockchain.Stellar -> "stellar" + Blockchain.StellarTestNet -> "stellar" else -> { throw Exception("Can''t get rate for blockchain " + ctx.blockchainName) } diff --git a/app/src/main/java/org/stellar/sdk/Account.java b/app/src/main/java/org/stellar/sdk/Account.java new file mode 100644 index 0000000000..42e5f35578 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Account.java @@ -0,0 +1,45 @@ +package org.stellar.sdk; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents an account in Stellar network with it's sequence number. + * Account object is required to build a {@link Transaction}. + * @see org.stellar.sdk.Transaction.Builder + */ +public class Account implements TransactionBuilderAccount { + private final KeyPair mKeyPair; + private Long mSequenceNumber; + + /** + * Class constructor. + * @param keypair KeyPair associated with this Account + * @param sequenceNumber Current sequence number of the account (can be obtained using java-stellar-sdk or horizon server) + */ + public Account(KeyPair keypair, Long sequenceNumber) { + mKeyPair = checkNotNull(keypair, "keypair cannot be null"); + mSequenceNumber = checkNotNull(sequenceNumber, "sequenceNumber cannot be null"); + } + + @Override + public KeyPair getKeypair() { + return mKeyPair; + } + + @Override + public Long getSequenceNumber() { + return mSequenceNumber; + } + + @Override + public Long getIncrementedSequenceNumber() { + return new Long(mSequenceNumber + 1); + } + + /** + * Increments sequence number in this object by one. + */ + public void incrementSequenceNumber() { + mSequenceNumber++; + } +} diff --git a/app/src/main/java/org/stellar/sdk/AccountFlag.java b/app/src/main/java/org/stellar/sdk/AccountFlag.java new file mode 100644 index 0000000000..16c941e837 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/AccountFlag.java @@ -0,0 +1,32 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AccountFlags; + +/** + * AccountFlag is the enum that can be used in {@link SetOptionsOperation}. + * @see Account Flags + */ +public enum AccountFlag { + /** + * Authorization required (0x1): Requires the issuing account to give other accounts permission before they can hold the issuing account’s credit. + */ + AUTH_REQUIRED_FLAG(AccountFlags.AUTH_REQUIRED_FLAG.getValue()), + /** + * Authorization revocable (0x2): Allows the issuing account to revoke its credit held by other accounts. + */ + AUTH_REVOCABLE_FLAG(AccountFlags.AUTH_REVOCABLE_FLAG.getValue()), + /** + * Authorization immutable (0x4): If this is set then none of the authorization flags can be set and the account can never be deleted. + */ + AUTH_IMMUTABLE_FLAG(AccountFlags.AUTH_IMMUTABLE_FLAG.getValue()), + ; + + private final int value; + AccountFlag(int value) { + this.value = value; + } + + public int getValue() { + return value; + } +} diff --git a/app/src/main/java/org/stellar/sdk/AccountMergeOperation.java b/app/src/main/java/org/stellar/sdk/AccountMergeOperation.java new file mode 100644 index 0000000000..9468ad71d1 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/AccountMergeOperation.java @@ -0,0 +1,80 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AccountID; +import org.stellar.sdk.xdr.Operation.OperationBody; +import org.stellar.sdk.xdr.OperationType; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents AccountMerge operation. + * @see List of Operations + */ +public class AccountMergeOperation extends Operation { + + private final KeyPair destination; + + private AccountMergeOperation(KeyPair destination) { + this.destination = checkNotNull(destination, "destination cannot be null"); + } + + /** + * The account that receives the remaining XLM balance of the source account. + */ + public KeyPair getDestination() { + return destination; + } + + @Override + OperationBody toOperationBody() { + OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + AccountID destination = new AccountID(); + destination.setAccountID(this.destination.getXdrPublicKey()); + body.setDestination(destination); + body.setDiscriminant(OperationType.ACCOUNT_MERGE); + return body; + } + + /** + * Builds AccountMerge operation. + * @see AccountMergeOperation + */ + public static class Builder { + private final KeyPair destination; + + private KeyPair mSourceAccount; + + Builder(OperationBody op) { + destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID()); + } + + /** + * Creates a new AccountMerge builder. + * @param destination The account that receives the remaining XLM balance of the source account. + */ + public Builder(KeyPair destination) { + this.destination = destination; + } + + /** + * Set source account of this operation + * @param sourceAccount Source account + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair sourceAccount) { + mSourceAccount = sourceAccount; + return this; + } + + /** + * Builds an operation + */ + public AccountMergeOperation build() { + AccountMergeOperation operation = new AccountMergeOperation(destination); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/AllowTrustOperation.java b/app/src/main/java/org/stellar/sdk/AllowTrustOperation.java new file mode 100644 index 0000000000..3752ea2f67 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/AllowTrustOperation.java @@ -0,0 +1,133 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AccountID; +import org.stellar.sdk.xdr.AllowTrustOp; +import org.stellar.sdk.xdr.AssetType; +import org.stellar.sdk.xdr.OperationType; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents AllowTrust operation. + * @see List of Operations + */ +public class AllowTrustOperation extends Operation { + + private final KeyPair trustor; + private final String assetCode; + private final boolean authorize; + + private AllowTrustOperation(KeyPair trustor, String assetCode, boolean authorize) { + this.trustor = checkNotNull(trustor, "trustor cannot be null"); + this.assetCode = checkNotNull(assetCode, "assetCode cannot be null"); + this.authorize = authorize; + } + + /** + * The account of the recipient of the trustline. + */ + public KeyPair getTrustor() { + return trustor; + } + + /** + * The asset of the trustline the source account is authorizing. For example, if a gateway wants to allow another account to hold its USD credit, the type is USD. + */ + public String getAssetCode() { + return assetCode; + } + + /** + * Flag indicating whether the trustline is authorized. + */ + public boolean getAuthorize() { + return authorize; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + AllowTrustOp op = new AllowTrustOp(); + + // trustor + AccountID trustor = new AccountID(); + trustor.setAccountID(this.trustor.getXdrPublicKey()); + op.setTrustor(trustor); + // asset + AllowTrustOp.AllowTrustOpAsset asset = new AllowTrustOp.AllowTrustOpAsset(); + if (assetCode.length() <= 4) { + asset.setDiscriminant(AssetType.ASSET_TYPE_CREDIT_ALPHANUM4); + asset.setAssetCode4(Util.paddedByteArray(assetCode, 4)); + } else { + asset.setDiscriminant(AssetType.ASSET_TYPE_CREDIT_ALPHANUM12); + asset.setAssetCode12(Util.paddedByteArray(assetCode, 12)); + } + op.setAsset(asset); + // authorize + op.setAuthorize(authorize); + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.ALLOW_TRUST); + body.setAllowTrustOp(op); + return body; + } + + /** + * Builds AllowTrust operation. + * @see AllowTrustOperation + */ + public static class Builder { + private final KeyPair trustor; + private final String assetCode; + private final boolean authorize; + + private KeyPair mSourceAccount; + + Builder(AllowTrustOp op) { + trustor = KeyPair.fromXdrPublicKey(op.getTrustor().getAccountID()); + switch (op.getAsset().getDiscriminant()) { + case ASSET_TYPE_CREDIT_ALPHANUM4: + assetCode = new String(op.getAsset().getAssetCode4()).trim(); + break; + case ASSET_TYPE_CREDIT_ALPHANUM12: + assetCode = new String(op.getAsset().getAssetCode12()).trim(); + break; + default: + throw new RuntimeException("Unknown asset code"); + } + authorize = op.getAuthorize(); + } + + /** + * Creates a new AllowTrust builder. + * @param trustor The account of the recipient of the trustline. + * @param assetCode The asset of the trustline the source account is authorizing. For example, if a gateway wants to allow another account to hold its USD credit, the type is USD. + * @param authorize Flag indicating whether the trustline is authorized. + */ + public Builder(KeyPair trustor, String assetCode, boolean authorize) { + this.trustor = trustor; + this.assetCode = assetCode; + this.authorize = authorize; + } + + /** + * Set source account of this operation + * @param sourceAccount Source account + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair sourceAccount) { + mSourceAccount = sourceAccount; + return this; + } + + /** + * Builds an operation + */ + public AllowTrustOperation build() { + AllowTrustOperation operation = new AllowTrustOperation(trustor, assetCode, authorize); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/Asset.java b/app/src/main/java/org/stellar/sdk/Asset.java new file mode 100644 index 0000000000..ebaa9069b0 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Asset.java @@ -0,0 +1,72 @@ +package org.stellar.sdk; + +/** + * Base Asset class. + * @see Assets + */ +public abstract class Asset { + Asset() {} + + public static Asset create(String type, String code, String issuer) { + if (type.equals("native")) { + return new AssetTypeNative(); + } else { + return Asset.createNonNativeAsset(code, KeyPair.fromAccountId(issuer)); + } + } + + /** + * Creates one of AssetTypeCreditAlphaNum4 or AssetTypeCreditAlphaNum12 object based on a code length + * @param code Asset code + * @param issuer Asset issuer + */ + public static Asset createNonNativeAsset(String code, KeyPair issuer) { + if (code.length() >= 1 && code.length() <= 4) { + return new AssetTypeCreditAlphaNum4(code, issuer); + } else if (code.length() >= 5 && code.length() <= 12) { + return new AssetTypeCreditAlphaNum12(code, issuer); + } else { + throw new AssetCodeLengthInvalidException(); + } + } + + /** + * Generates Asset object from a given XDR object + * @param xdr XDR object + */ + public static Asset fromXdr(org.stellar.sdk.xdr.Asset xdr) { + switch (xdr.getDiscriminant()) { + case ASSET_TYPE_NATIVE: + return new AssetTypeNative(); + case ASSET_TYPE_CREDIT_ALPHANUM4: + String assetCode4 = Util.paddedByteArrayToString(xdr.getAlphaNum4().getAssetCode()); + KeyPair issuer4 = KeyPair.fromXdrPublicKey( + xdr.getAlphaNum4().getIssuer().getAccountID()); + return new AssetTypeCreditAlphaNum4(assetCode4, issuer4); + case ASSET_TYPE_CREDIT_ALPHANUM12: + String assetCode12 = Util.paddedByteArrayToString(xdr.getAlphaNum12().getAssetCode()); + KeyPair issuer12 = KeyPair.fromXdrPublicKey(xdr.getAlphaNum12().getIssuer().getAccountID()); + return new AssetTypeCreditAlphaNum12(assetCode12, issuer12); + default: + throw new IllegalArgumentException("Unknown asset type " + xdr.getDiscriminant()); + } + } + + /** + * Returns asset type. Possible types: + *
    + *
  • native
  • + *
  • credit_alphanum4
  • + *
  • credit_alphanum12
  • + *
+ */ + public abstract String getType(); + + @Override + public abstract boolean equals(Object object); + + /** + * Generates XDR object from a given Asset object + */ + public abstract org.stellar.sdk.xdr.Asset toXdr(); +} diff --git a/app/src/main/java/org/stellar/sdk/AssetCodeLengthInvalidException.java b/app/src/main/java/org/stellar/sdk/AssetCodeLengthInvalidException.java new file mode 100644 index 0000000000..cee47af468 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/AssetCodeLengthInvalidException.java @@ -0,0 +1,16 @@ +package org.stellar.sdk; + +/** + * Indicates that asset code is not valid for a specified asset class + * @see AssetTypeCreditAlphaNum4 + * @see AssetTypeCreditAlphaNum12 + */ +public class AssetCodeLengthInvalidException extends RuntimeException { + public AssetCodeLengthInvalidException() { + super(); + } + + public AssetCodeLengthInvalidException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum.java b/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum.java new file mode 100644 index 0000000000..7607e60a80 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum.java @@ -0,0 +1,52 @@ +package org.stellar.sdk; + +import java.util.Arrays; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Base class for AssetTypeCreditAlphaNum4 and AssetTypeCreditAlphaNum12 subclasses. + * @see Assets + */ +public abstract class AssetTypeCreditAlphaNum extends Asset { + protected final String mCode; + protected final KeyPair mIssuer; + + public AssetTypeCreditAlphaNum(String code, KeyPair issuer) { + checkNotNull(code, "code cannot be null"); + checkNotNull(issuer, "issuer cannot be null"); + mCode = new String(code); + mIssuer = KeyPair.fromAccountId(issuer.getAccountId()); + } + + /** + * Returns asset code + */ + public String getCode() { + return new String(mCode); + } + + /** + * Returns asset issuer + */ + public KeyPair getIssuer() { + return KeyPair.fromAccountId(mIssuer.getAccountId()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(new Object[]{this.getCode(), this.getIssuer().getAccountId()}); + } + + @Override + public boolean equals(Object object) { + if (!this.getClass().equals(object.getClass())) { + return false; + } + + AssetTypeCreditAlphaNum o = (AssetTypeCreditAlphaNum) object; + + return this.getCode().equals(o.getCode()) && + this.getIssuer().getAccountId().equals(o.getIssuer().getAccountId()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum12.java b/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum12.java new file mode 100644 index 0000000000..41ba30b285 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum12.java @@ -0,0 +1,41 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AccountID; +import org.stellar.sdk.xdr.AssetType; + +/** + * Represents all assets with codes 5-12 characters long. + * @see Assets + */ +public final class AssetTypeCreditAlphaNum12 extends AssetTypeCreditAlphaNum { + + /** + * Class constructor + * @param code Asset code + * @param issuer Asset issuer + */ + public AssetTypeCreditAlphaNum12(String code, KeyPair issuer) { + super(code, issuer); + if (code.length() < 5 || code.length() > 12) { + throw new AssetCodeLengthInvalidException(); + } + } + + @Override + public String getType() { + return "credit_alphanum12"; + } + + @Override + public org.stellar.sdk.xdr.Asset toXdr() { + org.stellar.sdk.xdr.Asset xdr = new org.stellar.sdk.xdr.Asset(); + xdr.setDiscriminant(AssetType.ASSET_TYPE_CREDIT_ALPHANUM12); + org.stellar.sdk.xdr.Asset.AssetAlphaNum12 credit = new org.stellar.sdk.xdr.Asset.AssetAlphaNum12(); + credit.setAssetCode(Util.paddedByteArray(mCode, 12)); + AccountID accountID = new AccountID(); + accountID.setAccountID(mIssuer.getXdrPublicKey()); + credit.setIssuer(accountID); + xdr.setAlphaNum12(credit); + return xdr; + } +} diff --git a/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum4.java b/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum4.java new file mode 100644 index 0000000000..47a1589211 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/AssetTypeCreditAlphaNum4.java @@ -0,0 +1,41 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AccountID; +import org.stellar.sdk.xdr.AssetType; + +/** + * Represents all assets with codes 1-4 characters long. + * @see Assets + */ +public final class AssetTypeCreditAlphaNum4 extends AssetTypeCreditAlphaNum { + + /** + * Class constructor + * @param code Asset code + * @param issuer Asset issuer + */ + public AssetTypeCreditAlphaNum4(String code, KeyPair issuer) { + super(code, issuer); + if (code.length() < 1 || code.length() > 4) { + throw new AssetCodeLengthInvalidException(); + } + } + + @Override + public String getType() { + return "credit_alphanum4"; + } + + @Override + public org.stellar.sdk.xdr.Asset toXdr() { + org.stellar.sdk.xdr.Asset xdr = new org.stellar.sdk.xdr.Asset(); + xdr.setDiscriminant(AssetType.ASSET_TYPE_CREDIT_ALPHANUM4); + org.stellar.sdk.xdr.Asset.AssetAlphaNum4 credit = new org.stellar.sdk.xdr.Asset.AssetAlphaNum4(); + credit.setAssetCode(Util.paddedByteArray(mCode, 4)); + AccountID accountID = new AccountID(); + accountID.setAccountID(mIssuer.getXdrPublicKey()); + credit.setIssuer(accountID); + xdr.setAlphaNum4(credit); + return xdr; + } +} diff --git a/app/src/main/java/org/stellar/sdk/AssetTypeNative.java b/app/src/main/java/org/stellar/sdk/AssetTypeNative.java new file mode 100644 index 0000000000..a7fcbd4b08 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/AssetTypeNative.java @@ -0,0 +1,34 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AssetType; + +/** + * Represents Stellar native asset - lumens (XLM) + * @see Assets + */ +public final class AssetTypeNative extends Asset { + + public AssetTypeNative() {} + + @Override + public String getType() { + return "native"; + } + + @Override + public boolean equals(Object object) { + return this.getClass().equals(object.getClass()); + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public org.stellar.sdk.xdr.Asset toXdr() { + org.stellar.sdk.xdr.Asset xdr = new org.stellar.sdk.xdr.Asset(); + xdr.setDiscriminant(AssetType.ASSET_TYPE_NATIVE); + return xdr; + } +} diff --git a/app/src/main/java/org/stellar/sdk/BumpSequenceOperation.java b/app/src/main/java/org/stellar/sdk/BumpSequenceOperation.java new file mode 100644 index 0000000000..98b37d2077 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/BumpSequenceOperation.java @@ -0,0 +1,79 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.BumpSequenceOp; +import org.stellar.sdk.xdr.Int64; +import org.stellar.sdk.xdr.OperationType; +import org.stellar.sdk.xdr.SequenceNumber; + +import static com.google.common.base.Preconditions.checkNotNull; + +public class BumpSequenceOperation extends Operation { + private final long bumpTo; + + private BumpSequenceOperation(long bumpTo) { + this.bumpTo = bumpTo; + } + + public long getBumpTo() { + return bumpTo; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + BumpSequenceOp op = new BumpSequenceOp(); + Int64 bumpTo = new Int64(); + bumpTo.setInt64(this.bumpTo); + SequenceNumber sequenceNumber = new SequenceNumber(); + sequenceNumber.setSequenceNumber(bumpTo); + op.setBumpTo(sequenceNumber); + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.BUMP_SEQUENCE); + body.setBumpSequenceOp(op); + + return body; + } + + public static class Builder { + private final long bumpTo; + + private KeyPair mSourceAccount; + + /** + * Construct a new BumpSequence builder from a BumpSequence XDR. + * @param op {@link BumpSequenceOp} + */ + Builder(BumpSequenceOp op) { + bumpTo = op.getBumpTo().getSequenceNumber().getInt64(); + } + + /** + * Creates a new BumpSequence builder. + * @param bumpTo Sequence number to bump to + */ + public Builder(long bumpTo) { + this.bumpTo = bumpTo; + } + + /** + * Sets the source account for this operation. + * @param sourceAccount The operation's source account. + * @return Builder object so you can chain methods. + */ + public BumpSequenceOperation.Builder setSourceAccount(KeyPair sourceAccount) { + mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null"); + return this; + } + + /** + * Builds an operation + */ + public BumpSequenceOperation build() { + BumpSequenceOperation operation = new BumpSequenceOperation(bumpTo); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/ChangeTrustOperation.java b/app/src/main/java/org/stellar/sdk/ChangeTrustOperation.java new file mode 100644 index 0000000000..01eb78d3d3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/ChangeTrustOperation.java @@ -0,0 +1,98 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.ChangeTrustOp; +import org.stellar.sdk.xdr.Int64; +import org.stellar.sdk.xdr.OperationType; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents ChangeTrust operation. + * @see List of Operations + */ +public class ChangeTrustOperation extends Operation { + + private final Asset asset; + private final String limit; + + private ChangeTrustOperation(Asset asset, String limit) { + this.asset = checkNotNull(asset, "asset cannot be null"); + this.limit = checkNotNull(limit, "limit cannot be null"); + } + + /** + * The asset of the trustline. For example, if a gateway extends a trustline of up to 200 USD to a user, the line is USD. + */ + public Asset getAsset() { + return asset; + } + + /** + * The limit of the trustline. For example, if a gateway extends a trustline of up to 200 USD to a user, the limit is 200. + */ + public String getLimit() { + return limit; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + ChangeTrustOp op = new ChangeTrustOp(); + op.setLine(asset.toXdr()); + Int64 limit = new Int64(); + limit.setInt64(Operation.toXdrAmount(this.limit)); + op.setLimit(limit); + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.CHANGE_TRUST); + body.setChangeTrustOp(op); + return body; + } + + /** + * Builds ChangeTrust operation. + * @see ChangeTrustOperation + */ + public static class Builder { + private final Asset asset; + private final String limit; + + private KeyPair mSourceAccount; + + Builder(ChangeTrustOp op) { + asset = Asset.fromXdr(op.getLine()); + limit = Operation.fromXdrAmount(op.getLimit().getInt64().longValue()); + } + + /** + * Creates a new ChangeTrust builder. + * @param asset The asset of the trustline. For example, if a gateway extends a trustline of up to 200 USD to a user, the line is USD. + * @param limit The limit of the trustline. For example, if a gateway extends a trustline of up to 200 USD to a user, the limit is 200. + * @throws ArithmeticException when limit has more than 7 decimal places. + */ + public Builder(Asset asset, String limit) { + this.asset = checkNotNull(asset, "asset cannot be null"); + this.limit = checkNotNull(limit, "limit cannot be null"); + } + + /** + * Set source account of this operation + * @param sourceAccount Source account + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair sourceAccount) { + mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null"); + return this; + } + + /** + * Builds an operation + */ + public ChangeTrustOperation build() { + ChangeTrustOperation operation = new ChangeTrustOperation(asset, limit); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/CreateAccountOperation.java b/app/src/main/java/org/stellar/sdk/CreateAccountOperation.java new file mode 100644 index 0000000000..46c2e85284 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/CreateAccountOperation.java @@ -0,0 +1,105 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AccountID; +import org.stellar.sdk.xdr.CreateAccountOp; +import org.stellar.sdk.xdr.Int64; +import org.stellar.sdk.xdr.OperationType; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents CreateAccount operation. + * @see List of Operations + */ +public class CreateAccountOperation extends Operation { + + private final KeyPair destination; + private final String startingBalance; + + private CreateAccountOperation(KeyPair destination, String startingBalance) { + this.destination = checkNotNull(destination, "destination cannot be null"); + this.startingBalance = checkNotNull(startingBalance, "startingBalance cannot be null"); + } + + /** + * Amount of XLM to send to the newly created account. + */ + public String getStartingBalance() { + return startingBalance; + } + + /** + * Account that is created and funded + */ + public KeyPair getDestination() { + return destination; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + CreateAccountOp op = new CreateAccountOp(); + AccountID destination = new AccountID(); + destination.setAccountID(this.destination.getXdrPublicKey()); + op.setDestination(destination); + Int64 startingBalance = new Int64(); + startingBalance.setInt64(Operation.toXdrAmount(this.startingBalance)); + op.setStartingBalance(startingBalance); + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.CREATE_ACCOUNT); + body.setCreateAccountOp(op); + return body; + } + + /** + * Builds CreateAccount operation. + * @see CreateAccountOperation + */ + public static class Builder { + private final KeyPair destination; + private final String startingBalance; + + private KeyPair mSourceAccount; + + /** + * Construct a new CreateAccount builder from a CreateAccountOp XDR. + * @param op {@link CreateAccountOp} + */ + Builder(CreateAccountOp op) { + destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID()); + startingBalance = Operation.fromXdrAmount(op.getStartingBalance().getInt64().longValue()); + } + + /** + * Creates a new CreateAccount builder. + * @param destination The destination keypair (uses only the public key). + * @param startingBalance The initial balance to start with in lumens. + * @throws ArithmeticException when startingBalance has more than 7 decimal places. + */ + public Builder(KeyPair destination, String startingBalance) { + this.destination = destination; + this.startingBalance = startingBalance; + } + + /** + * Sets the source account for this operation. + * @param account The operation's source account. + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair account) { + mSourceAccount = account; + return this; + } + + /** + * Builds an operation + */ + public CreateAccountOperation build() { + CreateAccountOperation operation = new CreateAccountOperation(destination, startingBalance); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/CreatePassiveOfferOperation.java b/app/src/main/java/org/stellar/sdk/CreatePassiveOfferOperation.java new file mode 100644 index 0000000000..0d871e8ccd --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/CreatePassiveOfferOperation.java @@ -0,0 +1,136 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.CreatePassiveOfferOp; +import org.stellar.sdk.xdr.Int64; +import org.stellar.sdk.xdr.OperationType; + +import java.math.BigDecimal; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents CreatePassiveOffer operation. + * @see List of Operations + */ +public class CreatePassiveOfferOperation extends Operation { + private final Asset selling; + private final Asset buying; + private final String amount; + private final String price; + + private CreatePassiveOfferOperation(Asset selling, Asset buying, String amount, String price) { + this.selling = checkNotNull(selling, "selling cannot be null"); + this.buying = checkNotNull(buying, "buying cannot be null"); + this.amount = checkNotNull(amount, "amount cannot be null"); + this.price = checkNotNull(price, "price cannot be null"); + } + + /** + * The asset being sold in this operation + */ + public Asset getSelling() { + return selling; + } + + /** + * The asset being bought in this operation + */ + public Asset getBuying() { + return buying; + } + + /** + * Amount of selling being sold. + */ + public String getAmount() { + return amount; + } + + /** + * Price of 1 unit of selling in terms of buying. + */ + public String getPrice() { + return price; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + CreatePassiveOfferOp op = new CreatePassiveOfferOp(); + op.setSelling(selling.toXdr()); + op.setBuying(buying.toXdr()); + Int64 amount = new Int64(); + amount.setInt64(Operation.toXdrAmount(this.amount)); + op.setAmount(amount); + Price price = Price.fromString(this.price); + op.setPrice(price.toXdr()); + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.CREATE_PASSIVE_OFFER); + body.setCreatePassiveOfferOp(op); + + return body; + } + + /** + * Builds CreatePassiveOffer operation. + * @see CreatePassiveOfferOperation + */ + public static class Builder { + + private final Asset selling; + private final Asset buying; + private final String amount; + private final String price; + + private KeyPair mSourceAccount; + + /** + * Construct a new CreatePassiveOffer builder from a CreatePassiveOfferOp XDR. + * @param op + */ + Builder(CreatePassiveOfferOp op) { + selling = Asset.fromXdr(op.getSelling()); + buying = Asset.fromXdr(op.getBuying()); + amount = Operation.fromXdrAmount(op.getAmount().getInt64().longValue()); + int n = op.getPrice().getN().getInt32().intValue(); + int d = op.getPrice().getD().getInt32().intValue(); + price = new BigDecimal(n).divide(new BigDecimal(d)).toString(); + } + + /** + * Creates a new CreatePassiveOffer builder. + * @param selling The asset being sold in this operation + * @param buying The asset being bought in this operation + * @param amount Amount of selling being sold. + * @param price Price of 1 unit of selling in terms of buying. + * @throws ArithmeticException when amount has more than 7 decimal places. + */ + public Builder(Asset selling, Asset buying, String amount, String price) { + this.selling = checkNotNull(selling, "selling cannot be null"); + this.buying = checkNotNull(buying, "buying cannot be null"); + this.amount = checkNotNull(amount, "amount cannot be null"); + this.price = checkNotNull(price, "price cannot be null"); + } + + /** + * Sets the source account for this operation. + * @param sourceAccount The operation's source account. + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair sourceAccount) { + mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null"); + return this; + } + + /** + * Builds an operation + */ + public CreatePassiveOfferOperation build() { + CreatePassiveOfferOperation operation = new CreatePassiveOfferOperation(selling, buying, amount, price); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/FormatException.java b/app/src/main/java/org/stellar/sdk/FormatException.java new file mode 100644 index 0000000000..e3671e805d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/FormatException.java @@ -0,0 +1,15 @@ +package org.stellar.sdk; + +/** + * Indicates that there was a problem decoding strkey encoded string. + * @see KeyPair + */ +public class FormatException extends RuntimeException { + public FormatException() { + super(); + } + + public FormatException(String message) { + super(message); + } +} diff --git a/app/src/main/java/org/stellar/sdk/InflationOperation.java b/app/src/main/java/org/stellar/sdk/InflationOperation.java new file mode 100644 index 0000000000..b2ee39a0b5 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/InflationOperation.java @@ -0,0 +1,16 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.OperationType; + +/** + * Represents Inflation operation. + * @see List of Operations + */ +public class InflationOperation extends Operation { + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.INFLATION); + return body; + } +} diff --git a/app/src/main/java/org/stellar/sdk/KeyPair.java b/app/src/main/java/org/stellar/sdk/KeyPair.java new file mode 100644 index 0000000000..eea2efc262 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/KeyPair.java @@ -0,0 +1,262 @@ +package org.stellar.sdk; + +import net.i2p.crypto.eddsa.EdDSAEngine; +import net.i2p.crypto.eddsa.EdDSAPrivateKey; +import net.i2p.crypto.eddsa.EdDSAPublicKey; +import net.i2p.crypto.eddsa.KeyPairGenerator; +import net.i2p.crypto.eddsa.spec.EdDSANamedCurveSpec; +import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable; +import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec; +import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec; + +import org.stellar.sdk.xdr.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.SignatureException; +import java.util.Arrays; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Holds a Stellar keypair. + */ +public class KeyPair { + + private static final EdDSANamedCurveSpec ed25519 = EdDSANamedCurveTable.ED_25519_CURVE_SPEC; + + private final EdDSAPublicKey mPublicKey; + private final EdDSAPrivateKey mPrivateKey; + + /** + * Creates a new KeyPair without a private key. Useful to simply verify a signature from a + * given public address. + * @param publicKey + */ + public KeyPair(EdDSAPublicKey publicKey) { + this(publicKey, null); + } + + /** + * Creates a new KeyPair from the given public and private keys. + * @param publicKey + * @param privateKey + */ + public KeyPair(EdDSAPublicKey publicKey, EdDSAPrivateKey privateKey) { + mPublicKey = checkNotNull(publicKey, "publicKey cannot be null"); + mPrivateKey = privateKey; + } + + /** + * Returns true if this Keypair is capable of signing + */ + public boolean canSign() { + return mPrivateKey != null; + } + + /** + * Creates a new Stellar KeyPair from a strkey encoded Stellar secret seed. + * @param seed Char array containing strkey encoded Stellar secret seed. + * @return {@link KeyPair} + */ + public static KeyPair fromSecretSeed(char[] seed) { + byte[] decoded = StrKey.decodeStellarSecretSeed(seed); + KeyPair keypair = fromSecretSeed(decoded); + Arrays.fill(decoded, (byte) 0); + return keypair; + } + + /** + * Insecure Creates a new Stellar KeyPair from a strkey encoded Stellar secret seed. + * This method is insecure. Use only if you are aware of security implications. + * @see Using Password-Based Encryption + * @param seed The strkey encoded Stellar secret seed. + * @return {@link KeyPair} + */ + public static KeyPair fromSecretSeed(String seed) { + char[] charSeed = seed.toCharArray(); + byte[] decoded = StrKey.decodeStellarSecretSeed(charSeed); + KeyPair keypair = fromSecretSeed(decoded); + Arrays.fill(charSeed, ' '); + return keypair; + } + + /** + * Creates a new Stellar keypair from a raw 32 byte secret seed. + * @param seed The 32 byte secret seed. + * @return {@link KeyPair} + */ + public static KeyPair fromSecretSeed(byte[] seed) { + EdDSAPrivateKeySpec privKeySpec = new EdDSAPrivateKeySpec(seed, ed25519); + EdDSAPublicKeySpec publicKeySpec = new EdDSAPublicKeySpec(privKeySpec.getA().toByteArray(), ed25519); + return new KeyPair(new EdDSAPublicKey(publicKeySpec), new EdDSAPrivateKey(privKeySpec)); + } + + /** + * Creates a new Stellar KeyPair from a strkey encoded Stellar account ID. + * @param accountId The strkey encoded Stellar account ID. + * @return {@link KeyPair} + */ + public static KeyPair fromAccountId(String accountId) { + byte[] decoded = StrKey.decodeStellarAccountId(accountId); + return fromPublicKey(decoded); + } + + /** + * Creates a new Stellar keypair from a 32 byte address. + * @param publicKey The 32 byte public key. + * @return {@link KeyPair} + */ + public static KeyPair fromPublicKey(byte[] publicKey) { + EdDSAPublicKeySpec publicKeySpec = new EdDSAPublicKeySpec(publicKey, ed25519); + return new KeyPair(new EdDSAPublicKey(publicKeySpec)); + } + + /** + * Finds the KeyPair for the path m/44'/148'/accountNumber' using the method described in + * SEP-0005. + * + * @param bip39Seed The output of BIP0039 + * @param accountNumber The number of the account + * @return KeyPair with secret + */ + public static KeyPair fromBip39Seed(byte[] bip39Seed, int accountNumber) { + try { + return KeyPair.fromSecretSeed(SLIP10.deriveEd25519PrivateKey(bip39Seed, 44, 148, accountNumber)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Generates a random Stellar keypair. + * @return a random Stellar keypair. + */ + public static KeyPair random() { + java.security.KeyPair keypair = new KeyPairGenerator().generateKeyPair(); + return new KeyPair((EdDSAPublicKey) keypair.getPublic(), (EdDSAPrivateKey) keypair.getPrivate()); + } + + /** + * Returns the human readable account ID encoded in strkey. + */ + public String getAccountId() { + return StrKey.encodeStellarAccountId(mPublicKey.getAbyte()); + } + + /** + * Returns the human readable secret seed encoded in strkey. + */ + public char[] getSecretSeed() { + return StrKey.encodeStellarSecretSeed(mPrivateKey.getSeed()); + } + + public byte[] getPublicKey() { + return mPublicKey.getAbyte(); + } + + public SignatureHint getSignatureHint() { + try { + ByteArrayOutputStream publicKeyBytesStream = new ByteArrayOutputStream(); + XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(publicKeyBytesStream); + PublicKey.encode(xdrOutputStream, this.getXdrPublicKey()); + byte[] publicKeyBytes = publicKeyBytesStream.toByteArray(); + byte[] signatureHintBytes = Arrays.copyOfRange(publicKeyBytes, publicKeyBytes.length - 4, publicKeyBytes.length); + + SignatureHint signatureHint = new SignatureHint(); + signatureHint.setSignatureHint(signatureHintBytes); + return signatureHint; + } catch (IOException e) { + throw new AssertionError(e); + } + } + + public PublicKey getXdrPublicKey() { + PublicKey publicKey = new PublicKey(); + publicKey.setDiscriminant(PublicKeyType.PUBLIC_KEY_TYPE_ED25519); + Uint256 uint256 = new Uint256(); + uint256.setUint256(getPublicKey()); + publicKey.setEd25519(uint256); + return publicKey; + } + + public SignerKey getXdrSignerKey() { + SignerKey signerKey = new SignerKey(); + signerKey.setDiscriminant(SignerKeyType.SIGNER_KEY_TYPE_ED25519); + Uint256 uint256 = new Uint256(); + uint256.setUint256(getPublicKey()); + signerKey.setEd25519(uint256); + return signerKey; + } + + public static KeyPair fromXdrPublicKey(PublicKey key) { + return KeyPair.fromPublicKey(key.getEd25519().getUint256()); + } + + public static KeyPair fromXdrSignerKey(SignerKey key) { + return KeyPair.fromPublicKey(key.getEd25519().getUint256()); + } + + /** + * Sign the provided data with the keypair's private key. + * @param data The data to sign. + * @return signed bytes, null if the private key for this keypair is null. + */ + public byte[] sign(byte[] data) { + if (mPrivateKey == null) { + throw new RuntimeException("KeyPair does not contain secret key. Use KeyPair.fromSecretSeed method to create a new KeyPair with a secret key."); + } + try { + Signature sgr = new EdDSAEngine(MessageDigest.getInstance("SHA-512")); + sgr.initSign(mPrivateKey); + sgr.update(data); + return sgr.sign(); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + /** + * Sign the provided data with the keypair's private key and returns {@link DecoratedSignature}. + * @param data + */ + public DecoratedSignature signDecorated(byte[] data) { + byte[] signatureBytes = this.sign(data); + + org.stellar.sdk.xdr.Signature signature = new org.stellar.sdk.xdr.Signature(); + signature.setSignature(signatureBytes); + + DecoratedSignature decoratedSignature = new DecoratedSignature(); + decoratedSignature.setHint(this.getSignatureHint()); + decoratedSignature.setSignature(signature); + return decoratedSignature; + } + + /** + * Verify the provided data and signature match this keypair's public key. + * @param data The data that was signed. + * @param signature The signature. + * @return True if they match, false otherwise. + * @throws RuntimeException + */ + public boolean verify(byte[] data, byte[] signature) { + try { + Signature sgr = new EdDSAEngine(MessageDigest.getInstance("SHA-512")); + sgr.initVerify(mPublicKey); + sgr.update(data); + return sgr.verify(signature); + } catch (SignatureException e) { + return false; + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } +} diff --git a/app/src/main/java/org/stellar/sdk/ManageDataOperation.java b/app/src/main/java/org/stellar/sdk/ManageDataOperation.java new file mode 100644 index 0000000000..51528528e7 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/ManageDataOperation.java @@ -0,0 +1,107 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.DataValue; +import org.stellar.sdk.xdr.ManageDataOp; +import org.stellar.sdk.xdr.OperationType; +import org.stellar.sdk.xdr.String64; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents ManageData operation. + * @see List of Operations + */ +public class ManageDataOperation extends Operation { + private final String name; + private final byte[] value; + + private ManageDataOperation(String name, byte[] value) { + this.name = checkNotNull(name, "name cannot be null"); + this.value = value; + } + + /** + * The name of the data value + */ + public String getName() { + return name; + } + + /** + * Data value + */ + public byte[] getValue() { + return value; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + ManageDataOp op = new ManageDataOp(); + String64 name = new String64(); + name.setString64(this.name); + op.setDataName(name); + + if (value != null) { + DataValue dataValue = new DataValue(); + dataValue.setDataValue(this.value); + op.setDataValue(dataValue); + } + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.MANAGE_DATA); + body.setManageDataOp(op); + + return body; + } + + public static class Builder { + private final String name; + private final byte[] value; + + private KeyPair mSourceAccount; + + /** + * Construct a new ManageOffer builder from a ManageDataOp XDR. + * @param op {@link ManageDataOp} + */ + Builder(ManageDataOp op) { + name = op.getDataName().getString64(); + if (op.getDataValue() != null) { + value = op.getDataValue().getDataValue(); + } else { + value = null; + } + } + + /** + * Creates a new ManageData builder. If you want to delete data entry pass null as a value param. + * @param name The name of data entry + * @param value The value of data entry. nullnull will delete data entry. + */ + public Builder(String name, byte[] value) { + this.name = checkNotNull(name, "name cannot be null"); + this.value = value; + } + + /** + * Sets the source account for this operation. + * @param sourceAccount The operation's source account. + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair sourceAccount) { + mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null"); + return this; + } + + /** + * Builds an operation + */ + public ManageDataOperation build() { + ManageDataOperation operation = new ManageDataOperation(name, value); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/ManageOfferOperation.java b/app/src/main/java/org/stellar/sdk/ManageOfferOperation.java new file mode 100644 index 0000000000..317bd33078 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/ManageOfferOperation.java @@ -0,0 +1,165 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.CreateAccountOp; +import org.stellar.sdk.xdr.Int64; +import org.stellar.sdk.xdr.ManageOfferOp; +import org.stellar.sdk.xdr.OperationType; +import org.stellar.sdk.xdr.Uint64; + +import java.math.BigDecimal; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents ManageOffer operation. + * @see List of Operations + */ +public class ManageOfferOperation extends Operation { + + private final Asset selling; + private final Asset buying; + private final String amount; + private final String price; + private final long offerId; + + private ManageOfferOperation(Asset selling, Asset buying, String amount, String price, long offerId) { + this.selling = checkNotNull(selling, "selling cannot be null"); + this.buying = checkNotNull(buying, "buying cannot be null"); + this.amount = checkNotNull(amount, "amount cannot be null"); + this.price = checkNotNull(price, "price cannot be null"); + // offerId can be null + this.offerId = offerId; + } + + /** + * The asset being sold in this operation + */ + public Asset getSelling() { + return selling; + } + + /** + * The asset being bought in this operation + */ + public Asset getBuying() { + return buying; + } + + /** + * Amount of selling being sold. + */ + public String getAmount() { + return amount; + } + + /** + * Price of 1 unit of selling in terms of buying. + */ + public String getPrice() { + return price; + } + + /** + * The ID of the offer. + */ + public long getOfferId() { + return offerId; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + ManageOfferOp op = new ManageOfferOp(); + op.setSelling(selling.toXdr()); + op.setBuying(buying.toXdr()); + Int64 amount = new Int64(); + amount.setInt64(Operation.toXdrAmount(this.amount)); + op.setAmount(amount); + Price price = Price.fromString(this.price); + op.setPrice(price.toXdr()); + Uint64 offerId = new Uint64(); + offerId.setUint64(Long.valueOf(this.offerId)); + op.setOfferID(offerId); + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.MANAGE_OFFER); + body.setManageOfferOp(op); + + return body; + } + + /** + * Builds ManageOffer operation. If you want to update existing offer use + * {@link org.stellar.sdk.ManageOfferOperation.Builder#setOfferId(long)}. + * @see ManageOfferOperation + */ + public static class Builder { + + private final Asset selling; + private final Asset buying; + private final String amount; + private final String price; + private long offerId = 0; + + private KeyPair mSourceAccount; + + /** + * Construct a new CreateAccount builder from a CreateAccountOp XDR. + * @param op {@link CreateAccountOp} + */ + Builder(ManageOfferOp op) { + selling = Asset.fromXdr(op.getSelling()); + buying = Asset.fromXdr(op.getBuying()); + amount = Operation.fromXdrAmount(op.getAmount().getInt64().longValue()); + int n = op.getPrice().getN().getInt32().intValue(); + int d = op.getPrice().getD().getInt32().intValue(); + price = new BigDecimal(n).divide(new BigDecimal(d)).toString(); + offerId = op.getOfferID().getUint64().longValue(); + } + + /** + * Creates a new ManageOffer builder. If you want to update existing offer use + * {@link org.stellar.sdk.ManageOfferOperation.Builder#setOfferId(long)}. + * @param selling The asset being sold in this operation + * @param buying The asset being bought in this operation + * @param amount Amount of selling being sold. + * @param price Price of 1 unit of selling in terms of buying. + * @throws ArithmeticException when amount has more than 7 decimal places. + */ + public Builder(Asset selling, Asset buying, String amount, String price) { + this.selling = checkNotNull(selling, "selling cannot be null"); + this.buying = checkNotNull(buying, "buying cannot be null"); + this.amount = checkNotNull(amount, "amount cannot be null"); + this.price = checkNotNull(price, "price cannot be null"); + } + + /** + * Sets offer ID. 0 creates a new offer. Set to existing offer ID to change it. + * @param offerId + */ + public Builder setOfferId(long offerId) { + this.offerId = offerId; + return this; + } + + /** + * Sets the source account for this operation. + * @param sourceAccount The operation's source account. + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair sourceAccount) { + mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null"); + return this; + } + + /** + * Builds an operation + */ + public ManageOfferOperation build() { + ManageOfferOperation operation = new ManageOfferOperation(selling, buying, amount, price, offerId); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/Memo.java b/app/src/main/java/org/stellar/sdk/Memo.java new file mode 100644 index 0000000000..b0a5f9f35b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Memo.java @@ -0,0 +1,93 @@ +package org.stellar.sdk; + +import com.google.common.io.BaseEncoding; + +/** + *

The memo contains optional extra information. It is the responsibility of the client to interpret this value. Memos can be one of the following types:

+ *
    + *
  • MEMO_NONE: Empty memo.
  • + *
  • MEMO_TEXT: A string up to 28-bytes long.
  • + *
  • MEMO_ID: A 64 bit unsigned integer.
  • + *
  • MEMO_HASH: A 32 byte hash.
  • + *
  • MEMO_RETURN: A 32 byte hash intended to be interpreted as the hash of the transaction the sender is refunding.
  • + *
+ *

Use static methods to generate any of above types.

+ * @see Transaction + */ +public abstract class Memo { + /** + * Creates new MemoNone instance. + */ + public static MemoNone none() { + return new MemoNone(); + } + + /** + * Creates new {@link MemoText} instance. + * @param text + */ + public static MemoText text(String text) { + return new MemoText(text); + } + + /** + * Creates new {@link MemoId} instance. + * @param id + */ + public static MemoId id(long id) { + return new MemoId(id); + } + + /** + * Creates new {@link MemoHash} instance from byte array. + * @param bytes + */ + public static MemoHash hash(byte[] bytes) { + return new MemoHash(bytes); + } + + /** + * Creates new {@link MemoHash} instance from hex-encoded string + * @param hexString + */ + public static MemoHash hash(String hexString) { + return new MemoHash(hexString); + } + + /** + * Creates new {@link MemoReturnHash} instance from byte array. + * @param bytes + */ + public static MemoReturnHash returnHash(byte[] bytes) { + return new MemoReturnHash(bytes); + } + + /** + * Creates new {@link MemoReturnHash} instance from hex-encoded string. + * @param hexString + */ + public static MemoReturnHash returnHash(String hexString) { + // We change to lowercase because we want to decode both: upper cased and lower cased alphabets. + return new MemoReturnHash(BaseEncoding.base16().lowerCase().decode(hexString.toLowerCase())); + } + + public static Memo fromXdr(org.stellar.sdk.xdr.Memo memo) { + switch (memo.getDiscriminant()) { + case MEMO_NONE: + return none(); + case MEMO_ID: + return id(memo.getId().getUint64().longValue()); + case MEMO_TEXT: + return text(memo.getText()); + case MEMO_HASH: + return hash(memo.getHash().getHash()); + case MEMO_RETURN: + return returnHash(memo.getRetHash().getHash()); + default: + throw new RuntimeException("Unknown memo type"); + } + } + + abstract org.stellar.sdk.xdr.Memo toXdr(); + abstract public boolean equals(Object o); +} diff --git a/app/src/main/java/org/stellar/sdk/MemoHash.java b/app/src/main/java/org/stellar/sdk/MemoHash.java new file mode 100644 index 0000000000..f11e943d31 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/MemoHash.java @@ -0,0 +1,28 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.MemoType; + +/** + * Represents MEMO_HASH. + */ +public class MemoHash extends MemoHashAbstract { + public MemoHash(byte[] bytes) { + super(bytes); + } + + public MemoHash(String hexString) { + super(hexString); + } + + @Override + org.stellar.sdk.xdr.Memo toXdr() { + org.stellar.sdk.xdr.Memo memo = new org.stellar.sdk.xdr.Memo(); + memo.setDiscriminant(MemoType.MEMO_HASH); + + org.stellar.sdk.xdr.Hash hash = new org.stellar.sdk.xdr.Hash(); + hash.setHash(bytes); + + memo.setHash(hash); + return memo; + } +} diff --git a/app/src/main/java/org/stellar/sdk/MemoHashAbstract.java b/app/src/main/java/org/stellar/sdk/MemoHashAbstract.java new file mode 100644 index 0000000000..854def4b96 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/MemoHashAbstract.java @@ -0,0 +1,69 @@ +package org.stellar.sdk; + +import com.google.common.base.Objects; +import com.google.common.io.BaseEncoding; + +abstract class MemoHashAbstract extends Memo { + protected byte[] bytes; + + public MemoHashAbstract(byte[] bytes) { + if (bytes.length < 32) { + bytes = Util.paddedByteArray(bytes, 32); + } else if (bytes.length > 32) { + throw new MemoTooLongException("MEMO_HASH can contain 32 bytes at max."); + } + + this.bytes = bytes; + } + + public MemoHashAbstract(String hexString) { + // We change to lowercase because we want to decode both: upper cased and lower cased alphabets. + this(BaseEncoding.base16().lowerCase().decode(hexString.toLowerCase())); + } + + /** + * Returns 32 bytes long array contained in this memo. + */ + public byte[] getBytes() { + return bytes; + } + + /** + *

Returns hex representation of bytes contained in this memo.

+ * + *

Example:

+ * + * MemoHash memo = new MemoHash("4142434445"); + * memo.getHexValue(); // 4142434445000000000000000000000000000000000000000000000000000000 + * memo.getTrimmedHexValue(); // 4142434445 + * + */ + public String getHexValue() { + return BaseEncoding.base16().lowerCase().encode(this.bytes); + } + + /** + *

Returns hex representation of bytes contained in this memo until null byte (0x00) is found.

+ * + *

Example:

+ * + * MemoHash memo = new MemoHash("4142434445"); + * memo.getHexValue(); // 4142434445000000000000000000000000000000000000000000000000000000 + * memo.getTrimmedHexValue(); // 4142434445 + * + */ + public String getTrimmedHexValue() { + return this.getHexValue().split("00")[0]; + } + + @Override + abstract org.stellar.sdk.xdr.Memo toXdr(); + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MemoHashAbstract that = (MemoHashAbstract) o; + return Objects.equal(bytes, that.bytes); + } +} diff --git a/app/src/main/java/org/stellar/sdk/MemoId.java b/app/src/main/java/org/stellar/sdk/MemoId.java new file mode 100644 index 0000000000..4f6f0114bb --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/MemoId.java @@ -0,0 +1,40 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.MemoType; +import org.stellar.sdk.xdr.Uint64; + +/** + * Represents MEMO_ID. + */ +public class MemoId extends Memo { + private long id; + + public MemoId(long id) { + if (Long.compareUnsigned(id, 0) < 0) { + throw new IllegalArgumentException("id must be a positive number"); + } + this.id = id; + } + + public long getId() { + return id; + } + + @Override + org.stellar.sdk.xdr.Memo toXdr() { + org.stellar.sdk.xdr.Memo memo = new org.stellar.sdk.xdr.Memo(); + memo.setDiscriminant(MemoType.MEMO_ID); + Uint64 idXdr = new Uint64(); + idXdr.setUint64(id); + memo.setId(idXdr); + return memo; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MemoId memoId = (MemoId) o; + return id == memoId.id; + } +} diff --git a/app/src/main/java/org/stellar/sdk/MemoNone.java b/app/src/main/java/org/stellar/sdk/MemoNone.java new file mode 100644 index 0000000000..593b021e91 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/MemoNone.java @@ -0,0 +1,22 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.MemoType; + +/** + * Represents MEMO_NONE. + */ +public class MemoNone extends Memo { + @Override + org.stellar.sdk.xdr.Memo toXdr() { + org.stellar.sdk.xdr.Memo memo = new org.stellar.sdk.xdr.Memo(); + memo.setDiscriminant(MemoType.MEMO_NONE); + return memo; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + return true; + } +} diff --git a/app/src/main/java/org/stellar/sdk/MemoReturnHash.java b/app/src/main/java/org/stellar/sdk/MemoReturnHash.java new file mode 100644 index 0000000000..96a2347ad9 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/MemoReturnHash.java @@ -0,0 +1,29 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.Memo; +import org.stellar.sdk.xdr.MemoType; + +/** + * Represents MEMO_RETURN. + */ +public class MemoReturnHash extends MemoHashAbstract { + public MemoReturnHash(byte[] bytes) { + super(bytes); + } + + public MemoReturnHash(String hexString) { + super(hexString); + } + + @Override + Memo toXdr() { + org.stellar.sdk.xdr.Memo memo = new org.stellar.sdk.xdr.Memo(); + memo.setDiscriminant(MemoType.MEMO_RETURN); + + org.stellar.sdk.xdr.Hash hash = new org.stellar.sdk.xdr.Hash(); + hash.setHash(bytes); + + memo.setRetHash(hash); + return memo; + } +} diff --git a/app/src/main/java/org/stellar/sdk/MemoText.java b/app/src/main/java/org/stellar/sdk/MemoText.java new file mode 100644 index 0000000000..0dd1390d40 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/MemoText.java @@ -0,0 +1,44 @@ +package org.stellar.sdk; + +import com.google.common.base.Objects; +import org.stellar.sdk.xdr.MemoType; + +import java.nio.charset.Charset; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents MEMO_TEXT. + */ +public class MemoText extends Memo { + private String text; + + public MemoText(String text) { + this.text = checkNotNull(text, "text cannot be null"); + + int length = text.getBytes((Charset.forName("UTF-8"))).length; + if (length > 28) { + throw new MemoTooLongException("text must be <= 28 bytes. length=" + String.valueOf(length)); + } + } + + public String getText() { + return text; + } + + @Override + org.stellar.sdk.xdr.Memo toXdr() { + org.stellar.sdk.xdr.Memo memo = new org.stellar.sdk.xdr.Memo(); + memo.setDiscriminant(MemoType.MEMO_TEXT); + memo.setText(text); + return memo; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MemoText memoText = (MemoText) o; + return Objects.equal(text, memoText.text); + } +} diff --git a/app/src/main/java/org/stellar/sdk/MemoTooLongException.java b/app/src/main/java/org/stellar/sdk/MemoTooLongException.java new file mode 100644 index 0000000000..dd4d217071 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/MemoTooLongException.java @@ -0,0 +1,15 @@ +package org.stellar.sdk; + +/** + * Indicates that value passed to Memo + * @see Memo + */ +public class MemoTooLongException extends RuntimeException { + public MemoTooLongException() { + super(); + } + + public MemoTooLongException(String message) { + super(message); + } +} diff --git a/app/src/main/java/org/stellar/sdk/Network.java b/app/src/main/java/org/stellar/sdk/Network.java new file mode 100644 index 0000000000..35fa7556fb --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Network.java @@ -0,0 +1,71 @@ +package org.stellar.sdk; + +import java.nio.charset.Charset; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Network class is used to specify which Stellar network you want to use. + * Each network has a networkPassphrase which is hashed to + * every transaction id. + * There is no default network. You need to specify network when initializing your app by calling + * {@link Network#use(Network)}, {@link Network#usePublicNetwork()} or {@link Network#useTestNetwork()}. + */ +public class Network { + private final static String PUBLIC = "Public Global Stellar Network ; September 2015"; + private final static String TESTNET = "Test SDF Network ; September 2015"; + private static Network current; + + private final String networkPassphrase; + + /** + * Creates a new Network object to represent a network with a given passphrase + * @param networkPassphrase + */ + public Network(String networkPassphrase) { + this.networkPassphrase = checkNotNull(networkPassphrase, "networkPassphrase cannot be null"); + } + + /** + * Returns network passphrase + */ + public String getNetworkPassphrase() { + return networkPassphrase; + } + + /** + * Returns network id (SHA-256 hashed networkPassphrase). + */ + public byte[] getNetworkId() { + return Util.hash(current.getNetworkPassphrase().getBytes(Charset.forName("UTF-8"))); + } + + /** + * Returns currently used Network object. + */ + public static Network current() { + return current; + } + + /** + * Use network as a current network. + * @param network Network object to set as current network + */ + public static void use(Network network) { + current = network; + } + + /** + * Use Stellar Public Network + */ + public static void usePublicNetwork() { + Network.use(new Network(PUBLIC)); + } + + /** + * Use Stellar Test Network. + */ + public static void useTestNetwork() { + Network.use(new Network(TESTNET)); + } +} diff --git a/app/src/main/java/org/stellar/sdk/NoNetworkSelectedException.java b/app/src/main/java/org/stellar/sdk/NoNetworkSelectedException.java new file mode 100644 index 0000000000..a0caac4d12 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/NoNetworkSelectedException.java @@ -0,0 +1,10 @@ +package org.stellar.sdk; + +/** + * Indicates that no network was selected. + */ +public class NoNetworkSelectedException extends RuntimeException { + public NoNetworkSelectedException() { + super("No network selected. Use `Network.use`, `Network.usePublicNetwork` or `Network.useTestNetwork` helper methods to select network."); + } +} diff --git a/app/src/main/java/org/stellar/sdk/NotEnoughSignaturesException.java b/app/src/main/java/org/stellar/sdk/NotEnoughSignaturesException.java new file mode 100644 index 0000000000..7fa3b33ab7 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/NotEnoughSignaturesException.java @@ -0,0 +1,14 @@ +package org.stellar.sdk; + +/** + * Indicates that the object that has to be signed has not enough signatures. + */ +public class NotEnoughSignaturesException extends RuntimeException { + public NotEnoughSignaturesException() { + super(); + } + + public NotEnoughSignaturesException(String message) { + super(message); + } +} diff --git a/app/src/main/java/org/stellar/sdk/Operation.java b/app/src/main/java/org/stellar/sdk/Operation.java new file mode 100644 index 0000000000..a39ab13594 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Operation.java @@ -0,0 +1,134 @@ +package org.stellar.sdk; + +import com.google.common.io.BaseEncoding; +import org.stellar.sdk.xdr.AccountID; +import org.stellar.sdk.xdr.XdrDataOutputStream; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigDecimal; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Abstract class for operations. + */ +public abstract class Operation { + Operation() {} + + private KeyPair mSourceAccount; + + private static final BigDecimal ONE = new BigDecimal(10).pow(7); + + protected static long toXdrAmount(String value) { + value = checkNotNull(value, "value cannot be null"); + BigDecimal amount = new BigDecimal(value).multiply(Operation.ONE); + return amount.longValueExact(); + } + + protected static String fromXdrAmount(long value) { + BigDecimal amount = new BigDecimal(value).divide(Operation.ONE); + return amount.toPlainString(); + } + + /** + * Generates Operation XDR object. + */ + public org.stellar.sdk.xdr.Operation toXdr() { + org.stellar.sdk.xdr.Operation xdr = new org.stellar.sdk.xdr.Operation(); + if (getSourceAccount() != null) { + AccountID sourceAccount = new AccountID(); + sourceAccount.setAccountID(getSourceAccount().getXdrPublicKey()); + xdr.setSourceAccount(sourceAccount); + } + xdr.setBody(toOperationBody()); + return xdr; + } + + /** + * Returns base64-encoded Operation XDR object. + */ + public String toXdrBase64() { + try { + org.stellar.sdk.xdr.Operation operation = this.toXdr(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream); + org.stellar.sdk.xdr.Operation.encode(xdrOutputStream, operation); + BaseEncoding base64Encoding = BaseEncoding.base64(); + return base64Encoding.encode(outputStream.toByteArray()); + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /** + * Returns new Operation object from Operation XDR object. + * @param xdr XDR object + */ + public static Operation fromXdr(org.stellar.sdk.xdr.Operation xdr) { + org.stellar.sdk.xdr.Operation.OperationBody body = xdr.getBody(); + Operation operation; + switch (body.getDiscriminant()) { + case CREATE_ACCOUNT: + operation = new CreateAccountOperation.Builder(body.getCreateAccountOp()).build(); + break; + case PAYMENT: + operation = new PaymentOperation.Builder(body.getPaymentOp()).build(); + break; + case PATH_PAYMENT: + operation = new PathPaymentOperation.Builder(body.getPathPaymentOp()).build(); + break; + case MANAGE_OFFER: + operation = new ManageOfferOperation.Builder(body.getManageOfferOp()).build(); + break; + case CREATE_PASSIVE_OFFER: + operation = new CreatePassiveOfferOperation.Builder(body.getCreatePassiveOfferOp()).build(); + break; + case SET_OPTIONS: + operation = new SetOptionsOperation.Builder(body.getSetOptionsOp()).build(); + break; + case CHANGE_TRUST: + operation = new ChangeTrustOperation.Builder(body.getChangeTrustOp()).build(); + break; + case ALLOW_TRUST: + operation = new AllowTrustOperation.Builder(body.getAllowTrustOp()).build(); + break; + case ACCOUNT_MERGE: + operation = new AccountMergeOperation.Builder(body).build(); + break; + case MANAGE_DATA: + operation = new ManageDataOperation.Builder(body.getManageDataOp()).build(); + break; + case BUMP_SEQUENCE: + operation = new BumpSequenceOperation.Builder(body.getBumpSequenceOp()).build(); + break; + default: + throw new RuntimeException("Unknown operation body " + body.getDiscriminant()); + } + if (xdr.getSourceAccount() != null) { + operation.setSourceAccount(KeyPair.fromXdrPublicKey(xdr.getSourceAccount().getAccountID())); + } + return operation; + } + + /** + * Returns operation source account. + */ + public KeyPair getSourceAccount() { + return mSourceAccount; + } + + /** + * Sets operation source account. + * @param keypair + */ + void setSourceAccount(KeyPair keypair) { + mSourceAccount = checkNotNull(keypair, "keypair cannot be null"); + } + + /** + * Generates OperationBody XDR object + * @return OperationBody XDR object + */ + abstract org.stellar.sdk.xdr.Operation.OperationBody toOperationBody(); +} diff --git a/app/src/main/java/org/stellar/sdk/PathPaymentOperation.java b/app/src/main/java/org/stellar/sdk/PathPaymentOperation.java new file mode 100644 index 0000000000..5c67f8afd2 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/PathPaymentOperation.java @@ -0,0 +1,192 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AccountID; +import org.stellar.sdk.xdr.Int64; +import org.stellar.sdk.xdr.OperationType; +import org.stellar.sdk.xdr.PathPaymentOp; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents PathPayment operation. + * @see List of Operations + */ +public class PathPaymentOperation extends Operation { + + private final Asset sendAsset; + private final String sendMax; + private final KeyPair destination; + private final Asset destAsset; + private final String destAmount; + private final Asset[] path; + + private PathPaymentOperation(Asset sendAsset, String sendMax, KeyPair destination, + Asset destAsset, String destAmount, Asset[] path) { + this.sendAsset = checkNotNull(sendAsset, "sendAsset cannot be null"); + this.sendMax = checkNotNull(sendMax, "sendMax cannot be null"); + this.destination = checkNotNull(destination, "destination cannot be null"); + this.destAsset = checkNotNull(destAsset, "destAsset cannot be null"); + this.destAmount = checkNotNull(destAmount, "destAmount cannot be null"); + if (path == null) { + this.path = new Asset[0]; + } else { + checkArgument(path.length <= 5, "The maximum number of assets in the path is 5"); + this.path = path; + } + } + + /** + * The asset deducted from the sender's account. + */ + public Asset getSendAsset() { + return sendAsset; + } + + /** + * The maximum amount of send asset to deduct (excluding fees) + */ + public String getSendMax() { + return sendMax; + } + + /** + * Account that receives the payment. + */ + public KeyPair getDestination() { + return destination; + } + + /** + * The asset the destination account receives. + */ + public Asset getDestAsset() { + return destAsset; + } + + /** + * The amount of destination asset the destination account receives. + */ + public String getDestAmount() { + return destAmount; + } + + /** + * The assets (other than send asset and destination asset) involved in the offers the path takes. For example, if you can only find a path from USD to EUR through XLM and BTC, the path would be USD -» XLM -» BTC -» EUR and the path would contain XLM and BTC. + */ + public Asset[] getPath() { + return path; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + PathPaymentOp op = new PathPaymentOp(); + + // sendAsset + op.setSendAsset(sendAsset.toXdr()); + // sendMax + Int64 sendMax = new Int64(); + sendMax.setInt64(Operation.toXdrAmount(this.sendMax)); + op.setSendMax(sendMax); + // destination + AccountID destination = new AccountID(); + destination.setAccountID(this.destination.getXdrPublicKey()); + op.setDestination(destination); + // destAsset + op.setDestAsset(destAsset.toXdr()); + // destAmount + Int64 destAmount = new Int64(); + destAmount.setInt64(Operation.toXdrAmount(this.destAmount)); + op.setDestAmount(destAmount); + // path + org.stellar.sdk.xdr.Asset[] path = new org.stellar.sdk.xdr.Asset[this.path.length]; + for (int i = 0; i < this.path.length; i++) { + path[i] = this.path[i].toXdr(); + } + op.setPath(path); + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.PATH_PAYMENT); + body.setPathPaymentOp(op); + return body; + } + + /** + * Builds PathPayment operation. + * @see PathPaymentOperation + */ + public static class Builder { + private final Asset sendAsset; + private final String sendMax; + private final KeyPair destination; + private final Asset destAsset; + private final String destAmount; + private Asset[] path; + + private KeyPair mSourceAccount; + + Builder(PathPaymentOp op) { + sendAsset = Asset.fromXdr(op.getSendAsset()); + sendMax = Operation.fromXdrAmount(op.getSendMax().getInt64().longValue()); + destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID()); + destAsset = Asset.fromXdr(op.getDestAsset()); + destAmount = Operation.fromXdrAmount(op.getDestAmount().getInt64().longValue()); + path = new Asset[op.getPath().length]; + for (int i = 0; i < op.getPath().length; i++) { + path[i] = Asset.fromXdr(op.getPath()[i]); + } + } + + /** + * Creates a new PathPaymentOperation builder. + * @param sendAsset The asset deducted from the sender's account. + * @param sendMax The asset deducted from the sender's account. + * @param destination Payment destination + * @param destAsset The asset the destination account receives. + * @param destAmount The amount of destination asset the destination account receives. + * @throws ArithmeticException when sendMax or destAmount has more than 7 decimal places. + */ + public Builder(Asset sendAsset, String sendMax, KeyPair destination, + Asset destAsset, String destAmount) { + this.sendAsset = checkNotNull(sendAsset, "sendAsset cannot be null"); + this.sendMax = checkNotNull(sendMax, "sendMax cannot be null"); + this.destination = checkNotNull(destination, "destination cannot be null"); + this.destAsset = checkNotNull(destAsset, "destAsset cannot be null"); + this.destAmount = checkNotNull(destAmount, "destAmount cannot be null"); + } + + /** + * Sets path for this operation + * @param path The assets (other than send asset and destination asset) involved in the offers the path takes. For example, if you can only find a path from USD to EUR through XLM and BTC, the path would be USD -» XLM -» BTC -» EUR and the path field would contain XLM and BTC. + * @return Builder object so you can chain methods. + */ + public Builder setPath(Asset[] path) { + checkNotNull(path, "path cannot be null"); + checkArgument(path.length <= 5, "The maximum number of assets in the path is 5"); + this.path = path; + return this; + } + + /** + * Sets the source account for this operation. + * @param sourceAccount The operation's source account. + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair sourceAccount) { + mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null"); + return this; + } + + /** + * Builds an operation + */ + public PathPaymentOperation build() { + PathPaymentOperation operation = new PathPaymentOperation(sendAsset, sendMax, destination, + destAsset, destAmount, path); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/PaymentOperation.java b/app/src/main/java/org/stellar/sdk/PaymentOperation.java new file mode 100644 index 0000000000..1191fab6fd --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/PaymentOperation.java @@ -0,0 +1,123 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.AccountID; +import org.stellar.sdk.xdr.Int64; +import org.stellar.sdk.xdr.OperationType; +import org.stellar.sdk.xdr.PaymentOp; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents Payment operation. + * @see List of Operations + */ +public class PaymentOperation extends Operation { + + private final KeyPair destination; + private final Asset asset; + private final String amount; + + private PaymentOperation(KeyPair destination, Asset asset, String amount) { + this.destination = checkNotNull(destination, "destination cannot be null"); + this.asset = checkNotNull(asset, "asset cannot be null"); + this.amount = checkNotNull(amount, "amount cannot be null"); + } + + /** + * Account that receives the payment. + */ + public KeyPair getDestination() { + return destination; + } + + /** + * Asset to send to the destination account. + */ + public Asset getAsset() { + return asset; + } + + /** + * Amount of the asset to send. + */ + public String getAmount() { + return amount; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + PaymentOp op = new PaymentOp(); + + // destination + AccountID destination = new AccountID(); + destination.setAccountID(this.destination.getXdrPublicKey()); + op.setDestination(destination); + // asset + op.setAsset(asset.toXdr()); + // amount + Int64 amount = new Int64(); + amount.setInt64(Operation.toXdrAmount(this.amount)); + op.setAmount(amount); + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.PAYMENT); + body.setPaymentOp(op); + return body; + } + + /** + * Builds Payment operation. + * @see PathPaymentOperation + */ + public static class Builder { + private final KeyPair destination; + private final Asset asset; + private final String amount; + + private KeyPair mSourceAccount; + + /** + * Construct a new PaymentOperation builder from a PaymentOp XDR. + * @param op {@link PaymentOp} + */ + Builder(PaymentOp op) { + destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID()); + asset = Asset.fromXdr(op.getAsset()); + amount = Operation.fromXdrAmount(op.getAmount().getInt64().longValue()); + } + + /** + * Creates a new PaymentOperation builder. + * @param destination The destination keypair (uses only the public key). + * @param asset The asset to send. + * @param amount The amount to send in lumens. + * @throws ArithmeticException when amount has more than 7 decimal places. + */ + public Builder(KeyPair destination, Asset asset, String amount) { + this.destination = destination; + this.asset = asset; + this.amount = amount; + } + + /** + * Sets the source account for this operation. + * @param account The operation's source account. + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair account) { + mSourceAccount = account; + return this; + } + + /** + * Builds an operation + */ + public PaymentOperation build() { + PaymentOperation operation = new PaymentOperation(destination, asset, amount); + if (mSourceAccount != null) { + operation.setSourceAccount(mSourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/Price.java b/app/src/main/java/org/stellar/sdk/Price.java new file mode 100644 index 0000000000..1196d37446 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Price.java @@ -0,0 +1,110 @@ +package org.stellar.sdk; + +import com.google.gson.annotations.SerializedName; +import org.stellar.sdk.xdr.Int32; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents Price. Price in Stellar is represented as a fraction. + */ +public class Price { + @SerializedName("n") + private final int n; + @SerializedName("d") + private final int d; + + /** + * Create a new price. Price in Stellar is represented as a fraction. + * @param n numerator + * @param d denominator + */ + public Price(int n, int d) { + this.n = n; + this.d = d; + } + + /** + * Returns numerator. + */ + public int getNumerator() { + return n; + } + + /** + * Returns denominator + */ + public int getDenominator() { + return d; + } + + /** + * Approximates price to a fraction. + * Please remember that this function can give unexpected results for values that cannot be represented as a + * fraction with 32-bit numerator and denominator. It's safer to create a Price object using the constructor. + * @param price Ex. "1.25" + */ + public static Price fromString(String price) { + checkNotNull(price, "price cannot be null"); + BigDecimal maxInt = new BigDecimal(Integer.MAX_VALUE); + BigDecimal number = new BigDecimal(price); + BigDecimal a; + BigDecimal f; + List fractions = new ArrayList(); + fractions.add(new BigDecimal[]{new BigDecimal(0), new BigDecimal(1)}); + fractions.add(new BigDecimal[]{new BigDecimal(1), new BigDecimal(0)}); + int i = 2; + while (true) { + if (number.compareTo(maxInt) > 0) { + break; + } + a = number.setScale(0, BigDecimal.ROUND_FLOOR); + f = number.subtract(a); + BigDecimal h = a.multiply(fractions.get(i - 1)[0]).add(fractions.get(i - 2)[0]); + BigDecimal k = a.multiply(fractions.get(i - 1)[1]).add(fractions.get(i - 2)[1]); + if (h.compareTo(maxInt) > 0 || k.compareTo(maxInt) > 0) { + break; + } + fractions.add(new BigDecimal[]{h, k}); + if (f.compareTo(BigDecimal.ZERO) == 0) { + break; + } + number = new BigDecimal(1).divide(f, 20, BigDecimal.ROUND_HALF_UP); + i = i + 1; + } + BigDecimal n = fractions.get(fractions.size()-1)[0]; + BigDecimal d = fractions.get(fractions.size()-1)[1]; + return new Price(n.intValue(), d.intValue()); + } + + /** + * Generates Price XDR object. + */ + public org.stellar.sdk.xdr.Price toXdr() { + org.stellar.sdk.xdr.Price xdr = new org.stellar.sdk.xdr.Price(); + Int32 n = new Int32(); + Int32 d = new Int32(); + n.setInt32(this.n); + d.setInt32(this.d); + xdr.setN(n); + xdr.setD(d); + return xdr; + } + + @Override + public boolean equals(Object object) { + if (!(object instanceof Price)) { + return false; + } + + Price price = (Price) object; + + return this.getNumerator() == price.getNumerator() && + this.getDenominator() == price.getDenominator(); + + } +} diff --git a/app/src/main/java/org/stellar/sdk/SLIP10.java b/app/src/main/java/org/stellar/sdk/SLIP10.java new file mode 100644 index 0000000000..ba3649b763 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/SLIP10.java @@ -0,0 +1,65 @@ +package org.stellar.sdk; + +import javax.crypto.Mac; +import javax.crypto.ShortBufferException; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.Charset; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +final class SLIP10 { + + private SLIP10() { + } + + private static final String hmacSHA512algorithm = "HmacSHA512"; + + /** + * Derives only the private key for ED25519 in the manor defined in + * SLIP-0010. + * + * @param seed Seed, the BIP0039 output. + * @param indexes an array of indexes that define the path. E.g. for m/1'/2'/3', pass 1, 2, 3. + * As with Ed25519 non-hardened child indexes are not supported, this function treats all indexes + * as hardened. + * @return Private key. + * @throws NoSuchAlgorithmException If it cannot find the HmacSHA512 algorithm by name. + * @throws ShortBufferException Occurrence not expected. + * @throws InvalidKeyException Occurrence not expected. + */ + static byte[] deriveEd25519PrivateKey(final byte[] seed, final int... indexes) + throws NoSuchAlgorithmException, ShortBufferException, InvalidKeyException { + + final byte[] I = new byte[64]; + final Mac mac = Mac.getInstance(hmacSHA512algorithm); + + // I = HMAC-SHA512(Key = bytes("ed25519 seed"), Data = seed) + mac.init(new SecretKeySpec("ed25519 seed".getBytes(Charset.forName("UTF-8")), hmacSHA512algorithm)); + mac.update(seed); + mac.doFinal(I, 0); + + for (int i : indexes) { + // I = HMAC-SHA512(Key = c_par, Data = 0x00 || ser256(k_par) || ser32(i')) + // which is simply: + // I = HMAC-SHA512(Key = Ir, Data = 0x00 || Il || ser32(i')) + // Key = Ir + mac.init(new SecretKeySpec(I, 32, 32, hmacSHA512algorithm)); + // Data = 0x00 + mac.update((byte) 0x00); + // Data += Il + mac.update(I, 0, 32); + // Data += ser32(i') + mac.update((byte) (i >> 24 | 0x80)); + mac.update((byte) (i >> 16)); + mac.update((byte) (i >> 8)); + mac.update((byte) i); + // Write to I + mac.doFinal(I, 0); + } + + final byte[] Il = new byte[32]; + // copy head 32 bytes of I into Il + System.arraycopy(I, 0, Il, 0, 32); + return Il; + } +} diff --git a/app/src/main/java/org/stellar/sdk/Server.java b/app/src/main/java/org/stellar/sdk/Server.java new file mode 100644 index 0000000000..a33cb0ffac --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Server.java @@ -0,0 +1,203 @@ +package org.stellar.sdk; + +import com.google.gson.reflect.TypeToken; +import okhttp3.*; +import okhttp3.Response; +import org.stellar.sdk.requests.*; +import org.stellar.sdk.responses.*; + +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.concurrent.TimeUnit; + +/** + * Main class used to connect to Horizon server. + */ +public class Server { + private HttpUrl serverURI; + private OkHttpClient httpClient; + /** + * submitHttpClient is used only for submitting transactions. The read timeout is longer. + */ + private OkHttpClient submitHttpClient; + + /** + * HORIZON_SUBMIT_TIMEOUT is a time in seconds after Horizon sends a timeout response + * after internal txsub timeout. + */ + private static final int HORIZON_SUBMIT_TIMEOUT = 60; + + public Server(String uri) { + serverURI = HttpUrl.parse(uri); + httpClient = new OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .retryOnConnectionFailure(true) + .build(); + + submitHttpClient = new OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .readTimeout(HORIZON_SUBMIT_TIMEOUT + 5, TimeUnit.SECONDS) + .retryOnConnectionFailure(true) + .build(); + } + + + public OkHttpClient getHttpClient() { + return httpClient; + } + + public OkHttpClient getSubmitHttpClient() { + return submitHttpClient; + } + + public void setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + } + + public void setSubmitHttpClient(OkHttpClient submitHttpClient) { + this.submitHttpClient = submitHttpClient; + } + + /** + * Returns {@link RootResponse}. + */ + public RootResponse root() throws IOException { + TypeToken type = new TypeToken() {}; + ResponseHandler responseHandler = new ResponseHandler(type); + + Request request = new Request.Builder().get().url(serverURI).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Returns {@link AccountsRequestBuilder} instance. + */ + public AccountsRequestBuilder accounts() { + return new AccountsRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link AssetsRequestBuilder} instance. + */ + public AssetsRequestBuilder assets() { + return new AssetsRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link EffectsRequestBuilder} instance. + */ + public EffectsRequestBuilder effects() { + return new EffectsRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link LedgersRequestBuilder} instance. + */ + public LedgersRequestBuilder ledgers() { + return new LedgersRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link OffersRequestBuilder} instance. + */ + public OffersRequestBuilder offers() { + return new OffersRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link OperationsRequestBuilder} instance. + */ + public OperationsRequestBuilder operations() { + return new OperationsRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link OperationFeeStatsResponse} instance. + */ + public OperationFeeStatsRequestBuilder operationFeeStats() { + return new OperationFeeStatsRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link OrderBookRequestBuilder} instance. + */ + public OrderBookRequestBuilder orderBook() { + return new OrderBookRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link TradesRequestBuilder} instance. + */ + public TradesRequestBuilder trades() { + return new TradesRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link TradeAggregationsRequestBuilder} instance. + */ + public TradeAggregationsRequestBuilder tradeAggregations(Asset baseAsset, Asset counterAsset, long startTime, long endTime, long resolution, long offset) { + return new TradeAggregationsRequestBuilder(httpClient, serverURI, baseAsset, counterAsset, startTime, endTime, resolution, offset); + } + + /** + * Returns {@link PathsRequestBuilder} instance. + */ + public PathsRequestBuilder paths() { + return new PathsRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link PaymentsRequestBuilder} instance. + */ + public PaymentsRequestBuilder payments() { + return new PaymentsRequestBuilder(httpClient, serverURI); + } + + /** + * Returns {@link TransactionsRequestBuilder} instance. + */ + public TransactionsRequestBuilder transactions() { + return new TransactionsRequestBuilder(httpClient, serverURI); + } + + /** + * Submits transaction to the network. + * @param transaction transaction to submit to the network. + * @return {@link SubmitTransactionResponse} + * @throws SubmitTransactionTimeoutResponseException When Horizon returns a Timeout or connection timeout occured. + * @throws SubmitTransactionUnknownResponseException When unknown Horizon response is returned. + * @throws IOException + */ + public SubmitTransactionResponse submitTransaction(Transaction transaction) throws IOException { + HttpUrl transactionsURI = serverURI.newBuilder().addPathSegment("transactions").build(); + RequestBody requestBody = new FormBody.Builder().add("tx", transaction.toEnvelopeXdrBase64()).build(); + Request submitTransactionRequest = new Request.Builder().url(transactionsURI).post(requestBody).build(); + + Response response = null; + SubmitTransactionResponse submitTransactionResponse = null; + try { + response = this.submitHttpClient.newCall(submitTransactionRequest).execute(); + switch (response.code()) { + case 200: + case 400: + submitTransactionResponse = GsonSingleton.getInstance().fromJson(response.body().string(), SubmitTransactionResponse.class); + break; + case 504: + throw new SubmitTransactionTimeoutResponseException(); + default: + throw new SubmitTransactionUnknownResponseException(response.code(), response.body().string()); + } + } catch (SocketTimeoutException e) { + throw new SubmitTransactionTimeoutResponseException(); + } finally { + if (response != null) { + response.close(); + } + } + + return submitTransactionResponse; + } +} diff --git a/app/src/main/java/org/stellar/sdk/SetOptionsOperation.java b/app/src/main/java/org/stellar/sdk/SetOptionsOperation.java new file mode 100644 index 0000000000..0c59029b41 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/SetOptionsOperation.java @@ -0,0 +1,343 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.*; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents SetOptions operation. + * @see List of Operations + */ +public class SetOptionsOperation extends Operation { + + private final KeyPair inflationDestination; + private final Integer clearFlags; + private final Integer setFlags; + private final Integer masterKeyWeight; + private final Integer lowThreshold; + private final Integer mediumThreshold; + private final Integer highThreshold; + private final String homeDomain; + private final SignerKey signer; + private final Integer signerWeight; + + private SetOptionsOperation(KeyPair inflationDestination, Integer clearFlags, Integer setFlags, + Integer masterKeyWeight, Integer lowThreshold, Integer mediumThreshold, + Integer highThreshold, String homeDomain, SignerKey signer, Integer signerWeight) { + this.inflationDestination = inflationDestination; + this.clearFlags = clearFlags; + this.setFlags = setFlags; + this.masterKeyWeight = masterKeyWeight; + this.lowThreshold = lowThreshold; + this.mediumThreshold = mediumThreshold; + this.highThreshold = highThreshold; + this.homeDomain = homeDomain; + this.signer = signer; + this.signerWeight = signerWeight; + } + + /** + * Account of the inflation destination. + */ + public KeyPair getInflationDestination() { + return inflationDestination; + } + + /** + * Indicates which flags to clear. For details about the flags, please refer to the accounts doc. + * You can also use {@link AccountFlag} enum. + */ + public Integer getClearFlags() { + return clearFlags; + } + + /** + * Indicates which flags to set. For details about the flags, please refer to the accounts doc. + * You can also use {@link AccountFlag} enum. + */ + public Integer getSetFlags() { + return setFlags; + } + + /** + * Weight of the master key. + */ + public Integer getMasterKeyWeight() { + return masterKeyWeight; + } + + /** + * A number from 0-255 representing the threshold this account sets on all operations it performs that have a low threshold. + */ + public Integer getLowThreshold() { + return lowThreshold; + } + + /** + * A number from 0-255 representing the threshold this account sets on all operations it performs that have a medium threshold. + */ + public Integer getMediumThreshold() { + return mediumThreshold; + } + + /** + * A number from 0-255 representing the threshold this account sets on all operations it performs that have a high threshold. + */ + public Integer getHighThreshold() { + return highThreshold; + } + + /** + * The home domain of an account. + */ + public String getHomeDomain() { + return homeDomain; + } + + /** + * Additional signer added/removed in this operation. + */ + public SignerKey getSigner() { + return signer; + } + + /** + * Additional signer weight. The signer is deleted if the weight is 0. + */ + public Integer getSignerWeight() { + return signerWeight; + } + + @Override + org.stellar.sdk.xdr.Operation.OperationBody toOperationBody() { + SetOptionsOp op = new SetOptionsOp(); + if (inflationDestination != null) { + AccountID inflationDestination = new AccountID(); + inflationDestination.setAccountID(this.inflationDestination.getXdrPublicKey()); + op.setInflationDest(inflationDestination); + } + if (clearFlags != null) { + Uint32 clearFlags = new Uint32(); + clearFlags.setUint32(this.clearFlags); + op.setClearFlags(clearFlags); + } + if (setFlags != null) { + Uint32 setFlags = new Uint32(); + setFlags.setUint32(this.setFlags); + op.setSetFlags(setFlags); + } + if (masterKeyWeight != null) { + Uint32 uint32 = new Uint32(); + uint32.setUint32(masterKeyWeight); + op.setMasterWeight(uint32); + } + if (lowThreshold != null) { + Uint32 uint32 = new Uint32(); + uint32.setUint32(lowThreshold); + op.setLowThreshold(uint32); + } + if (mediumThreshold != null) { + Uint32 uint32 = new Uint32(); + uint32.setUint32(mediumThreshold); + op.setMedThreshold(uint32); + } + if (highThreshold != null) { + Uint32 uint32 = new Uint32(); + uint32.setUint32(highThreshold); + op.setHighThreshold(uint32); + } + if (homeDomain != null) { + String32 homeDomain = new String32(); + homeDomain.setString32(this.homeDomain); + op.setHomeDomain(homeDomain); + } + if (signer != null) { + org.stellar.sdk.xdr.Signer signer = new org.stellar.sdk.xdr.Signer(); + Uint32 weight = new Uint32(); + weight.setUint32(signerWeight & 0xFF); + signer.setKey(this.signer); + signer.setWeight(weight); + op.setSigner(signer); + } + + org.stellar.sdk.xdr.Operation.OperationBody body = new org.stellar.sdk.xdr.Operation.OperationBody(); + body.setDiscriminant(OperationType.SET_OPTIONS); + body.setSetOptionsOp(op); + return body; + } + + /** + * Builds SetOptions operation. + * @see SetOptionsOperation + */ + public static class Builder { + private KeyPair inflationDestination; + private Integer clearFlags; + private Integer setFlags; + private Integer masterKeyWeight; + private Integer lowThreshold; + private Integer mediumThreshold; + private Integer highThreshold; + private String homeDomain; + private SignerKey signer; + private Integer signerWeight; + private KeyPair sourceAccount; + + Builder(SetOptionsOp op) { + if (op.getInflationDest() != null) { + inflationDestination = KeyPair.fromXdrPublicKey( + op.getInflationDest().getAccountID()); + } + if (op.getClearFlags() != null) { + clearFlags = op.getClearFlags().getUint32(); + } + if (op.getSetFlags() != null) { + setFlags = op.getSetFlags().getUint32(); + } + if (op.getMasterWeight() != null) { + masterKeyWeight = op.getMasterWeight().getUint32().intValue(); + } + if (op.getLowThreshold() != null) { + lowThreshold = op.getLowThreshold().getUint32().intValue(); + } + if (op.getMedThreshold() != null) { + mediumThreshold = op.getMedThreshold().getUint32().intValue(); + } + if (op.getHighThreshold() != null) { + highThreshold = op.getHighThreshold().getUint32().intValue(); + } + if (op.getHomeDomain() != null) { + homeDomain = op.getHomeDomain().getString32(); + } + if (op.getSigner() != null) { + signer = op.getSigner().getKey(); + signerWeight = op.getSigner().getWeight().getUint32().intValue() & 0xFF; + } + } + + /** + * Creates a new SetOptionsOperation builder. + */ + public Builder() {} + + /** + * Sets the inflation destination for the account. + * @param inflationDestination The inflation destination account. + * @return Builder object so you can chain methods. + */ + public Builder setInflationDestination(KeyPair inflationDestination) { + this.inflationDestination = inflationDestination; + return this; + } + + /** + * Clears the given flags from the account. + * @param clearFlags For details about the flags, please refer to the accounts doc. + * @return Builder object so you can chain methods. + */ + public Builder setClearFlags(int clearFlags) { + this.clearFlags = clearFlags; + return this; + } + + /** + * Sets the given flags on the account. + * @param setFlags For details about the flags, please refer to the accounts doc. + * @return Builder object so you can chain methods. + */ + public Builder setSetFlags(int setFlags) { + this.setFlags = setFlags; + return this; + } + + /** + * Weight of the master key. + * @param masterKeyWeight Number between 0 and 255 + * @return Builder object so you can chain methods. + */ + public Builder setMasterKeyWeight(int masterKeyWeight) { + this.masterKeyWeight = masterKeyWeight; + return this; + } + + /** + * A number from 0-255 representing the threshold this account sets on all operations it performs that have a low threshold. + * @param lowThreshold Number between 0 and 255 + * @return Builder object so you can chain methods. + */ + public Builder setLowThreshold(int lowThreshold) { + this.lowThreshold = lowThreshold; + return this; + } + + /** + * A number from 0-255 representing the threshold this account sets on all operations it performs that have a medium threshold. + * @param mediumThreshold Number between 0 and 255 + * @return Builder object so you can chain methods. + */ + public Builder setMediumThreshold(int mediumThreshold) { + this.mediumThreshold = mediumThreshold; + return this; + } + + /** + * A number from 0-255 representing the threshold this account sets on all operations it performs that have a high threshold. + * @param highThreshold Number between 0 and 255 + * @return Builder object so you can chain methods. + */ + public Builder setHighThreshold(int highThreshold) { + this.highThreshold = highThreshold; + return this; + } + + /** + * Sets the account's home domain address used in Federation. + * @param homeDomain A string of the address which can be up to 32 characters. + * @return Builder object so you can chain methods. + */ + public Builder setHomeDomain(String homeDomain) { + if (homeDomain.length() > 32) { + throw new IllegalArgumentException("Home domain must be <= 32 characters"); + } + this.homeDomain = homeDomain; + return this; + } + + /** + * Add, update, or remove a signer from the account. Signer is deleted if the weight = 0; + * @param signer The signer key. Use {@link org.stellar.sdk.Signer} helper to create this object. + * @param weight The weight to attach to the signer (0-255). + * @return Builder object so you can chain methods. + */ + public Builder setSigner(SignerKey signer, Integer weight) { + checkNotNull(signer, "signer cannot be null"); + checkNotNull(weight, "weight cannot be null"); + this.signer = signer; + signerWeight = weight & 0xFF; + return this; + } + + /** + * Sets the source account for this operation. + * @param sourceAccount The operation's source account. + * @return Builder object so you can chain methods. + */ + public Builder setSourceAccount(KeyPair sourceAccount) { + this.sourceAccount = sourceAccount; + return this; + } + + /** + * Builds an operation + */ + public SetOptionsOperation build() { + SetOptionsOperation operation = new SetOptionsOperation(inflationDestination, clearFlags, + setFlags, masterKeyWeight, lowThreshold, mediumThreshold, highThreshold, + homeDomain, signer, signerWeight); + if (sourceAccount != null) { + operation.setSourceAccount(sourceAccount); + } + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/Signer.java b/app/src/main/java/org/stellar/sdk/Signer.java new file mode 100644 index 0000000000..8f1e91ecfb --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Signer.java @@ -0,0 +1,83 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.SignerKey; +import org.stellar.sdk.xdr.SignerKeyType; +import org.stellar.sdk.xdr.Uint256; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Signer is a helper class that creates {@link org.stellar.sdk.xdr.SignerKey} objects. + */ +public class Signer { + /** + * Create ed25519PublicKey {@link org.stellar.sdk.xdr.SignerKey} from + * a {@link org.stellar.sdk.KeyPair} + * @param keyPair + * @return org.stellar.sdk.xdr.SignerKey + */ + public static SignerKey ed25519PublicKey(KeyPair keyPair) { + checkNotNull(keyPair, "keyPair cannot be null"); + return keyPair.getXdrSignerKey(); + } + + /** + * Create sha256Hash {@link org.stellar.sdk.xdr.SignerKey} from + * a sha256 hash of a preimage. + * @param hash + * @return org.stellar.sdk.xdr.SignerKey + */ + public static SignerKey sha256Hash(byte[] hash) { + checkNotNull(hash, "hash cannot be null"); + SignerKey signerKey = new SignerKey(); + Uint256 value = Signer.createUint256(hash); + + signerKey.setDiscriminant(SignerKeyType.SIGNER_KEY_TYPE_HASH_X); + signerKey.setHashX(value); + + return signerKey; + } + + /** + * Create preAuthTx {@link org.stellar.sdk.xdr.SignerKey} from + * a {@link org.stellar.sdk.xdr.Transaction} hash. + * @param tx + * @return org.stellar.sdk.xdr.SignerKey + */ + public static SignerKey preAuthTx(Transaction tx) { + checkNotNull(tx, "tx cannot be null"); + SignerKey signerKey = new SignerKey(); + Uint256 value = Signer.createUint256(tx.hash()); + + signerKey.setDiscriminant(SignerKeyType.SIGNER_KEY_TYPE_PRE_AUTH_TX); + signerKey.setPreAuthTx(value); + + return signerKey; + } + + /** + * Create preAuthTx {@link org.stellar.sdk.xdr.SignerKey} from + * a transaction hash. + * @param hash + * @return org.stellar.sdk.xdr.SignerKey + */ + public static SignerKey preAuthTx(byte[] hash) { + checkNotNull(hash, "hash cannot be null"); + SignerKey signerKey = new SignerKey(); + Uint256 value = Signer.createUint256(hash); + + signerKey.setDiscriminant(SignerKeyType.SIGNER_KEY_TYPE_PRE_AUTH_TX); + signerKey.setPreAuthTx(value); + + return signerKey; + } + + private static Uint256 createUint256(byte[] hash) { + if (hash.length != 32) { + throw new RuntimeException("hash must be 32 bytes long"); + } + Uint256 value = new Uint256(); + value.setUint256(hash); + return value; + } +} diff --git a/app/src/main/java/org/stellar/sdk/StrKey.java b/app/src/main/java/org/stellar/sdk/StrKey.java new file mode 100644 index 0000000000..7b2f258f16 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/StrKey.java @@ -0,0 +1,157 @@ +package org.stellar.sdk; + +import com.google.common.io.BaseEncoding; + +import java.io.*; +import java.util.Arrays; + +class StrKey { + public enum VersionByte { + ACCOUNT_ID((byte)(6 << 3)), // G + SEED((byte)(18 << 3)), // S + PRE_AUTH_TX((byte)(19 << 3)), // T + SHA256_HASH((byte)(23 << 3)); // X + private final byte value; + VersionByte(byte value) { + this.value = value; + } + public int getValue() { + return value; + } + } + + private static BaseEncoding base32Encoding = BaseEncoding.base32().upperCase().omitPadding(); + + public static String encodeStellarAccountId(byte[] data) { + char[] encoded = encodeCheck(VersionByte.ACCOUNT_ID, data); + return String.valueOf(encoded); + } + + public static byte[] decodeStellarAccountId(String data) { + return decodeCheck(VersionByte.ACCOUNT_ID, data.toCharArray()); + } + + public static char[] encodeStellarSecretSeed(byte[] data) { + return encodeCheck(VersionByte.SEED, data); + } + + public static byte[] decodeStellarSecretSeed(char[] data) { + return decodeCheck(VersionByte.SEED, data); + } + + public static String encodePreAuthTx(byte[] data) { + char[] encoded = encodeCheck(VersionByte.PRE_AUTH_TX, data); + return String.valueOf(encoded); + } + + public static byte[] decodePreAuthTx(String data) { + return decodeCheck(VersionByte.PRE_AUTH_TX, data.toCharArray()); + } + + public static String encodeSha256Hash(byte[] data) { + char[] encoded = encodeCheck(VersionByte.SHA256_HASH, data); + return String.valueOf(encoded); + } + + public static byte[] decodeSha256Hash(String data) { + return decodeCheck(VersionByte.SHA256_HASH, data.toCharArray()); + } + + protected static char[] encodeCheck(VersionByte versionByte, byte[] data) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + outputStream.write(versionByte.getValue()); + outputStream.write(data); + byte payload[] = outputStream.toByteArray(); + byte checksum[] = StrKey.calculateChecksum(payload); + outputStream.write(checksum); + byte unencoded[] = outputStream.toByteArray(); + + // Why not use base32Encoding.encode here? + // We don't want secret seed to be stored as String in memory because of security reasons. It's impossible + // to erase it from memory when we want it to be erased (ASAP). + CharArrayWriter charArrayWriter = new CharArrayWriter(unencoded.length); + OutputStream charOutputStream = StrKey.base32Encoding.encodingStream(charArrayWriter); + charOutputStream.write(unencoded); + char[] charsEncoded = charArrayWriter.toCharArray(); + + if (VersionByte.SEED == versionByte) { + Arrays.fill(unencoded, (byte) 0); + Arrays.fill(payload, (byte) 0); + Arrays.fill(checksum, (byte) 0); + + // Clean charArrayWriter internal buffer + int bufferSize = charArrayWriter.size(); + char[] zeros = new char[bufferSize]; + Arrays.fill(zeros, '0'); + charArrayWriter.reset(); + charArrayWriter.write(zeros); + } + + return charsEncoded; + } catch (IOException e) { + throw new AssertionError(e); + } + } + + protected static byte[] decodeCheck(VersionByte versionByte, char[] encoded) { + byte[] bytes = new byte[encoded.length]; + for (int i = 0; i < encoded.length; i++) { + if (encoded[i] > 127) { + throw new IllegalArgumentException("Illegal characters in encoded char array."); + } + bytes[i] = (byte) encoded[i]; + } + + byte[] decoded = StrKey.base32Encoding.decode(java.nio.CharBuffer.wrap(encoded)); + byte decodedVersionByte = decoded[0]; + byte[] payload = Arrays.copyOfRange(decoded, 0, decoded.length-2); + byte[] data = Arrays.copyOfRange(payload, 1, payload.length); + byte[] checksum = Arrays.copyOfRange(decoded, decoded.length-2, decoded.length); + + if (decodedVersionByte != versionByte.getValue()) { + throw new FormatException("Version byte is invalid"); + } + + byte[] expectedChecksum = StrKey.calculateChecksum(payload); + + if (!Arrays.equals(expectedChecksum, checksum)) { + throw new FormatException("Checksum invalid"); + } + + if (VersionByte.SEED.getValue() == decodedVersionByte) { + Arrays.fill(bytes, (byte) 0); + Arrays.fill(decoded, (byte) 0); + Arrays.fill(payload, (byte) 0); + } + + return data; + } + + protected static byte[] calculateChecksum(byte[] bytes) { + // This code calculates CRC16-XModem checksum + // Ported from https://github.com/alexgorbatchev/node-crc + int crc = 0x0000; + int count = bytes.length; + int i = 0; + int code; + + while (count > 0) { + code = crc >>> 8 & 0xFF; + code ^= bytes[i++] & 0xFF; + code ^= code >>> 4; + crc = crc << 8 & 0xFFFF; + crc ^= code; + code = code << 5 & 0xFFFF; + crc ^= code; + code = code << 7 & 0xFFFF; + crc ^= code; + count--; + } + + // little-endian + return new byte[] { + (byte)crc, + (byte)(crc >>> 8)}; + } +} diff --git a/app/src/main/java/org/stellar/sdk/TimeBounds.java b/app/src/main/java/org/stellar/sdk/TimeBounds.java new file mode 100644 index 0000000000..e6451af979 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/TimeBounds.java @@ -0,0 +1,66 @@ +package org.stellar.sdk; + +import org.stellar.sdk.xdr.Uint64; + +/** + *

TimeBounds represents the time interval that a transaction is valid.

+ * @see Transaction + */ +final public class TimeBounds { + final private long mMinTime; + final private long mMaxTime; + + /** + * @param minTime 64bit Unix timestamp + * @param maxTime 64bit Unix timestamp + */ + public TimeBounds(long minTime, long maxTime) { + if (maxTime > 0 && minTime >= maxTime) { + throw new IllegalArgumentException("minTime must be >= maxTime"); + } + + mMinTime = minTime; + mMaxTime = maxTime; + } + + public long getMinTime() { + return mMinTime; + } + + public long getMaxTime() { + return mMaxTime; + } + + public static TimeBounds fromXdr(org.stellar.sdk.xdr.TimeBounds timeBounds) { + if (timeBounds == null) { + return null; + } + + return new TimeBounds( + timeBounds.getMinTime().getUint64().longValue(), + timeBounds.getMaxTime().getUint64().longValue() + ); + } + + public org.stellar.sdk.xdr.TimeBounds toXdr() { + org.stellar.sdk.xdr.TimeBounds timeBounds = new org.stellar.sdk.xdr.TimeBounds(); + Uint64 minTime = new Uint64(); + Uint64 maxTime = new Uint64(); + minTime.setUint64(mMinTime); + maxTime.setUint64(mMaxTime); + timeBounds.setMinTime(minTime); + timeBounds.setMaxTime(maxTime); + return timeBounds; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + TimeBounds that = (TimeBounds) o; + + if (mMinTime != that.mMinTime) return false; + return mMaxTime == that.mMaxTime; + } +} diff --git a/app/src/main/java/org/stellar/sdk/Transaction.java b/app/src/main/java/org/stellar/sdk/Transaction.java new file mode 100644 index 0000000000..7074b6655a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Transaction.java @@ -0,0 +1,381 @@ +package org.stellar.sdk; + +import com.google.common.io.BaseEncoding; +import org.stellar.sdk.xdr.*; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents Transaction in Stellar network. + */ +public class Transaction { + private static final int BASE_FEE = 100; + + protected final int mFee; + protected final KeyPair mSourceAccount; + protected final long mSequenceNumber; + protected final Operation[] mOperations; + protected final Memo mMemo; + protected final TimeBounds mTimeBounds; + protected List mSignatures; + + Transaction(KeyPair sourceAccount, int fee, long sequenceNumber, Operation[] operations, Memo memo, TimeBounds timeBounds) { + mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null"); + mSequenceNumber = checkNotNull(sequenceNumber, "sequenceNumber cannot be null"); + mOperations = checkNotNull(operations, "operations cannot be null"); + checkArgument(operations.length > 0, "At least one operation required"); + + mFee = fee; + mSignatures = new ArrayList(); + mMemo = memo != null ? memo : Memo.none(); + mTimeBounds = timeBounds; + } + + /** + * Adds a new signature ed25519PublicKey to this transaction. + * @param signer {@link KeyPair} object representing a signer + */ + public void sign(KeyPair signer) { + checkNotNull(signer, "signer cannot be null"); + byte[] txHash = this.hash(); + mSignatures.add(signer.signDecorated(txHash)); + } + + /** + * Adds a new sha256Hash signature to this transaction by revealing preimage. + * @param preimage the sha256 hash of preimage should be equal to signer hash + */ + public void sign(byte[] preimage) { + checkNotNull(preimage, "preimage cannot be null"); + org.stellar.sdk.xdr.Signature signature = new org.stellar.sdk.xdr.Signature(); + signature.setSignature(preimage); + + byte[] hash = Util.hash(preimage); + byte[] signatureHintBytes = Arrays.copyOfRange(hash, hash.length - 4, hash.length); + SignatureHint signatureHint = new SignatureHint(); + signatureHint.setSignatureHint(signatureHintBytes); + + DecoratedSignature decoratedSignature = new DecoratedSignature(); + decoratedSignature.setHint(signatureHint); + decoratedSignature.setSignature(signature); + + mSignatures.add(decoratedSignature); + } + + /** + * Returns transaction hash. + */ + public byte[] hash() { + return Util.hash(this.signatureBase()); + } + + /** + * Returns signature base. + */ + public byte[] signatureBase() { + if (Network.current() == null) { + throw new NoNetworkSelectedException(); + } + + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + // Hashed NetworkID + outputStream.write(Network.current().getNetworkId()); + // Envelope Type - 4 bytes + outputStream.write(ByteBuffer.allocate(4).putInt(EnvelopeType.ENVELOPE_TYPE_TX.getValue()).array()); + // Transaction XDR bytes + ByteArrayOutputStream txOutputStream = new ByteArrayOutputStream(); + XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(txOutputStream); + org.stellar.sdk.xdr.Transaction.encode(xdrOutputStream, this.toXdr()); + outputStream.write(txOutputStream.toByteArray()); + + return outputStream.toByteArray(); + } catch (IOException exception) { + return null; + } + } + + public KeyPair getSourceAccount() { + return mSourceAccount; + } + + public long getSequenceNumber() { + return mSequenceNumber; + } + + public List getSignatures() { + return mSignatures; + } + + public Memo getMemo() { + return mMemo; + } + + /** + * @return TimeBounds, or null (representing no time restrictions) + */ + public TimeBounds getTimeBounds() { + return mTimeBounds; + } + + /** + * Returns fee paid for transaction in stroops (1 stroop = 0.0000001 XLM). + */ + public int getFee() { + return mFee; + } + + /** + * Returns operations in this transaction. + */ + public Operation[] getOperations() { + return mOperations; + } + + /** + * Generates Transaction XDR object. + */ + public org.stellar.sdk.xdr.Transaction toXdr() { + // fee + org.stellar.sdk.xdr.Uint32 fee = new org.stellar.sdk.xdr.Uint32(); + fee.setUint32(mFee); + // sequenceNumber + org.stellar.sdk.xdr.Int64 sequenceNumberUint = new org.stellar.sdk.xdr.Int64(); + sequenceNumberUint.setInt64(mSequenceNumber); + org.stellar.sdk.xdr.SequenceNumber sequenceNumber = new org.stellar.sdk.xdr.SequenceNumber(); + sequenceNumber.setSequenceNumber(sequenceNumberUint); + // sourceAccount + org.stellar.sdk.xdr.AccountID sourceAccount = new org.stellar.sdk.xdr.AccountID(); + sourceAccount.setAccountID(mSourceAccount.getXdrPublicKey()); + // operations + org.stellar.sdk.xdr.Operation[] operations = new org.stellar.sdk.xdr.Operation[mOperations.length]; + for (int i = 0; i < mOperations.length; i++) { + operations[i] = mOperations[i].toXdr(); + } + // ext + org.stellar.sdk.xdr.Transaction.TransactionExt ext = new org.stellar.sdk.xdr.Transaction.TransactionExt(); + ext.setDiscriminant(0); + + org.stellar.sdk.xdr.Transaction transaction = new org.stellar.sdk.xdr.Transaction(); + transaction.setFee(fee); + transaction.setSeqNum(sequenceNumber); + transaction.setSourceAccount(sourceAccount); + transaction.setOperations(operations); + transaction.setMemo(mMemo.toXdr()); + transaction.setTimeBounds(mTimeBounds == null ? null : mTimeBounds.toXdr()); + transaction.setExt(ext); + return transaction; + } + + /** + * Creates a Transaction instance from previously build TransactionEnvelope + * @param envelope Base-64 encoded TransactionEnvelope + * @return + * @throws IOException + */ + public static Transaction fromEnvelopeXdr(String envelope) throws IOException { + BaseEncoding base64Encoding = BaseEncoding.base64(); + byte[] bytes = base64Encoding.decode(envelope); + + TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes))); + return fromEnvelopeXdr(transactionEnvelope); + } + + /** + * Creates a Transaction instance from previously build TransactionEnvelope + * @param envelope + * @return + */ + public static Transaction fromEnvelopeXdr(TransactionEnvelope envelope) { + org.stellar.sdk.xdr.Transaction tx = envelope.getTx(); + int mFee = tx.getFee().getUint32(); + KeyPair mSourceAccount = KeyPair.fromXdrPublicKey(tx.getSourceAccount().getAccountID()); + Long mSequenceNumber = tx.getSeqNum().getSequenceNumber().getInt64(); + Memo mMemo = Memo.fromXdr(tx.getMemo()); + TimeBounds mTimeBounds = TimeBounds.fromXdr(tx.getTimeBounds()); + + Operation[] mOperations = new Operation[tx.getOperations().length]; + for (int i = 0; i < tx.getOperations().length; i++) { + mOperations[i] = Operation.fromXdr(tx.getOperations()[i]); + } + + Transaction transaction = new Transaction(mSourceAccount, mFee, mSequenceNumber, mOperations, mMemo, mTimeBounds); + + for (DecoratedSignature signature : envelope.getSignatures()) { + transaction.mSignatures.add(signature); + } + + return transaction; + } + + /** + * Generates TransactionEnvelope XDR object. Transaction need to have at least one signature. + */ + public org.stellar.sdk.xdr.TransactionEnvelope toEnvelopeXdr() { + if (mSignatures.size() == 0) { + throw new NotEnoughSignaturesException("Transaction must be signed by at least one signer. Use transaction.sign()."); + } + + org.stellar.sdk.xdr.TransactionEnvelope xdr = new org.stellar.sdk.xdr.TransactionEnvelope(); + org.stellar.sdk.xdr.Transaction transaction = this.toXdr(); + xdr.setTx(transaction); + + DecoratedSignature[] signatures = new DecoratedSignature[mSignatures.size()]; + signatures = mSignatures.toArray(signatures); + xdr.setSignatures(signatures); + return xdr; + } + + /** + * Returns base64-encoded TransactionEnvelope XDR object. Transaction need to have at least one signature. + */ + public String toEnvelopeXdrBase64() { + try { + org.stellar.sdk.xdr.TransactionEnvelope envelope = this.toEnvelopeXdr(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream); + org.stellar.sdk.xdr.TransactionEnvelope.encode(xdrOutputStream, envelope); + + BaseEncoding base64Encoding = BaseEncoding.base64(); + return base64Encoding.encode(outputStream.toByteArray()); + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /** + * Builds a new Transaction object. + */ + public static class Builder { + private final TransactionBuilderAccount mSourceAccount; + private Memo mMemo; + private TimeBounds mTimeBounds; + List mOperations; + private boolean timeoutSet; + + public static final long TIMEOUT_INFINITE = 0; + + /** + * Construct a new transaction builder. + * @param sourceAccount The source account for this transaction. This account is the account + * who will use a sequence number. When build() is called, the account object's sequence number + * will be incremented. + */ + public Builder(TransactionBuilderAccount sourceAccount) { + checkNotNull(sourceAccount, "sourceAccount cannot be null"); + mSourceAccount = sourceAccount; + mOperations = Collections.synchronizedList(new ArrayList()); + } + + public int getOperationsCount() { + return mOperations.size(); + } + + /** + * Adds a new operation to this transaction. + * @param operation + * @return Builder object so you can chain methods. + * @see Operation + */ + public Builder addOperation(Operation operation) { + checkNotNull(operation, "operation cannot be null"); + mOperations.add(operation); + return this; + } + + /** + * Adds a memo to this transaction. + * @param memo + * @return Builder object so you can chain methods. + * @see Memo + */ + public Builder addMemo(Memo memo) { + if (mMemo != null) { + throw new RuntimeException("Memo has been already added."); + } + checkNotNull(memo, "memo cannot be null"); + mMemo = memo; + return this; + } + + /** + * Adds a time-bounds to this transaction. + * @param timeBounds + * @return Builder object so you can chain methods. + * @see TimeBounds + */ + public Builder addTimeBounds(TimeBounds timeBounds) { + if (mTimeBounds != null) { + throw new RuntimeException("TimeBounds has been already added."); + } + checkNotNull(timeBounds, "timeBounds cannot be null"); + mTimeBounds = timeBounds; + return this; + } + + /** + * Because of the distributed nature of the Stellar network it is possible that the status of your transaction + * will be determined after a long time if the network is highly congested. + * If you want to be sure to receive the status of the transaction within a given period you should set the + * {@link TimeBounds} with maxTime on the transaction (this is what setTimeout does + * internally; if there's minTime set but no maxTime it will be added). + * Call to Builder.setTimeout is required if Transaction does not have max_time set. + * If you don't want to set timeout, use TIMEOUT_INFINITE. In general you should set + * TIMEOUT_INFINITE only in smart contracts. + * Please note that Horizon may still return 504 Gateway Timeout error, even for short timeouts. + * In such case you need to resubmit the same transaction again without making any changes to receive a status. + * This method is using the machine system time (UTC), make sure it is set correctly. + * @param timeout Timeout in seconds. + * @see TimeBounds + * @return + */ + public Builder setTimeout(long timeout) { + if (mTimeBounds != null && mTimeBounds.getMaxTime() > 0) { + throw new RuntimeException("TimeBounds.max_time has been already set - setting timeout would overwrite it."); + } + + if (timeout < 0) { + throw new RuntimeException("timeout cannot be negative"); + } + + timeoutSet = true; + if (timeout > 0) { + long timeoutTimestamp = System.currentTimeMillis() / 1000L + timeout; + if (mTimeBounds == null) { + mTimeBounds = new TimeBounds(0, timeoutTimestamp); + } else { + mTimeBounds = new TimeBounds(mTimeBounds.getMinTime(), timeoutTimestamp); + } + } + + return this; + } + + /** + * Builds a transaction. It will increment sequence number of the source account. + */ + public Transaction build() { + // Ensure setTimeout called or maxTime is set + if ((mTimeBounds == null || mTimeBounds != null && mTimeBounds.getMaxTime() == 0) && !timeoutSet) { + throw new RuntimeException("TimeBounds has to be set or you must call setTimeout(TIMEOUT_INFINITE)."); + } + + Operation[] operations = new Operation[mOperations.size()]; + operations = mOperations.toArray(operations); + Transaction transaction = new Transaction(mSourceAccount.getKeypair(), operations.length * BASE_FEE, mSourceAccount.getIncrementedSequenceNumber(), operations, mMemo, mTimeBounds); + // Increment sequence number when there were no exceptions when creating a transaction + mSourceAccount.incrementSequenceNumber(); + return transaction; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/TransactionBuilderAccount.java b/app/src/main/java/org/stellar/sdk/TransactionBuilderAccount.java new file mode 100644 index 0000000000..e514b9aa36 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/TransactionBuilderAccount.java @@ -0,0 +1,26 @@ +package org.stellar.sdk; + +/** + * Specifies interface for Account object used in {@link org.stellar.sdk.Transaction.Builder} + */ +public interface TransactionBuilderAccount { + /** + * Returns keypair associated with this Account + */ + KeyPair getKeypair(); + + /** + * Returns current sequence number ot this Account. + */ + Long getSequenceNumber(); + + /** + * Returns sequence number incremented by one, but does not increment internal counter. + */ + Long getIncrementedSequenceNumber(); + + /** + * Increments sequence number in this object by one. + */ + void incrementSequenceNumber(); +} diff --git a/app/src/main/java/org/stellar/sdk/TransactionEx.java b/app/src/main/java/org/stellar/sdk/TransactionEx.java new file mode 100644 index 0000000000..9c898d2765 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/TransactionEx.java @@ -0,0 +1,75 @@ +package org.stellar.sdk; + +import org.stellar.sdk.responses.AccountResponse; +import org.stellar.sdk.xdr.DecoratedSignature; +import org.stellar.sdk.xdr.PublicKey; +import org.stellar.sdk.xdr.PublicKeyType; +import org.stellar.sdk.xdr.SignatureHint; +import org.stellar.sdk.xdr.Uint256; +import org.stellar.sdk.xdr.XdrDataOutputStream; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; + +public class TransactionEx extends Transaction { + public TransactionEx(KeyPair sourceAccount, int fee, long sequenceNumber, Operation[] operations, Memo memo, TimeBounds timeBounds) { + super(sourceAccount, fee, sequenceNumber, operations, memo, timeBounds); + } + + /** + * Builds a transaction. It will increment sequence number of the source account. + */ + public static TransactionEx buildEx(int timeout, AccountResponse sourceAccount, Operation operation) + { + long timeoutTimestamp = System.currentTimeMillis() / 1000L + timeout; + TimeBounds mTimeBounds = new TimeBounds(0, timeoutTimestamp); + + Operation[] operations = new Operation[1]; + operations[0] = operation; + TransactionEx transaction = new TransactionEx(sourceAccount.getKeypair(), operations.length * 100, sourceAccount.getIncrementedSequenceNumber(), operations, Memo.text(""), mTimeBounds); + // Increment sequence number when there were no exceptions when creating a transaction + sourceAccount.incrementSequenceNumber(); + return transaction; + } + + public PublicKey getXdrPublicKey() { + PublicKey publicKey = new PublicKey(); + publicKey.setDiscriminant(PublicKeyType.PUBLIC_KEY_TYPE_ED25519); + Uint256 uint256 = new Uint256(); + uint256.setUint256(mSourceAccount.getPublicKey()); + publicKey.setEd25519(uint256); + return publicKey; + } + + public SignatureHint getSignatureHint() { + try { + ByteArrayOutputStream publicKeyBytesStream = new ByteArrayOutputStream(); + XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(publicKeyBytesStream); + PublicKey.encode(xdrOutputStream, this.getXdrPublicKey()); + byte[] publicKeyBytes = publicKeyBytesStream.toByteArray(); + byte[] signatureHintBytes = Arrays.copyOfRange(publicKeyBytes, publicKeyBytes.length - 4, publicKeyBytes.length); + + SignatureHint signatureHint = new SignatureHint(); + signatureHint.setSignatureHint(signatureHintBytes); + return signatureHint; + } catch (IOException e) { + throw new AssertionError(e); + } + } + + public void setSign(byte[] signFromCard) { +// byte[] txHash = this.hash(); + + byte[] signatureBytes = signFromCard;//this.sign(txHash); + + org.stellar.sdk.xdr.Signature signature = new org.stellar.sdk.xdr.Signature(); + signature.setSignature(signatureBytes); + + DecoratedSignature decoratedSignature = new DecoratedSignature(); + decoratedSignature.setHint(this.getSignatureHint()); + decoratedSignature.setSignature(signature); + + mSignatures.add(decoratedSignature); + } +} diff --git a/app/src/main/java/org/stellar/sdk/Util.java b/app/src/main/java/org/stellar/sdk/Util.java new file mode 100644 index 0000000000..44875a27a2 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/Util.java @@ -0,0 +1,73 @@ +package org.stellar.sdk; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + +class Util { + + public static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); + + public static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for ( int j = 0; j < bytes.length; j++ ) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = HEX_ARRAY[v >>> 4]; + hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; + } + return new String(hexChars); + } + + public static byte[] hexToBytes(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i+1), 16)); + } + return data; + } + + /** + * Returns SHA-256 hash of data. + * @param data + */ + public static byte[] hash(byte[] data) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(data); + return md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("SHA-256 not implemented"); + } + } + + /** + * Pads bytes array to length with zeros. + * @param bytes + * @param length + */ + static byte[] paddedByteArray(byte[] bytes, int length) { + byte[] finalBytes = new byte[length]; + Arrays.fill(finalBytes, (byte) 0); + System.arraycopy(bytes, 0, finalBytes, 0, bytes.length); + return finalBytes; + } + + /** + * Pads string to length with zeros. + * @param string + * @param length + */ + static byte[] paddedByteArray(String string, int length) { + return Util.paddedByteArray(string.getBytes(), length); + } + + /** + * Remove zeros from the end of bytes array. + * @param bytes + */ + static String paddedByteArrayToString(byte[] bytes) { + return new String(bytes).split("\0")[0]; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/AccountsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/AccountsRequestBuilder.java new file mode 100644 index 0000000000..9718f9ea8d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/AccountsRequestBuilder.java @@ -0,0 +1,107 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.AccountResponse; +import org.stellar.sdk.responses.Page; + +import java.io.IOException; + +/** + * Builds requests connected to accounts. + */ +public class AccountsRequestBuilder extends RequestBuilder { + public AccountsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "accounts"); + } + + /** + * Requests specific uri and returns {@link AccountResponse}. + * This method is helpful for getting the links. + * @throws IOException + */ + public AccountResponse account(HttpUrl uri) throws IOException { + TypeToken type = new TypeToken() {}; + ResponseHandler responseHandler = new ResponseHandler(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Requests GET /accounts/{account} + * @see Account Details + * @param account Account to fetch + * @throws IOException + */ + public AccountResponse account(KeyPair account) throws IOException { + this.setSegments("accounts", account.getAccountId()); + return this.account(this.buildUri()); + } + + /** + * Requests specific uri and returns {@link Page} of {@link AccountResponse}. + * This method is helpful for getting the next set of results. + * @return {@link Page} of {@link AccountResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Allows to stream SSE events from horizon. + * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events. + * This mode will keep the connection to horizon open and horizon will continue to return + * responses as ledgers close. + * @see Server-Sent Events + * @see Response Format documentation + * @param listener {@link EventListener} implementation with {@link AccountResponse} type + * @return EventSource object, so you can close() connection when not needed anymore + */ + public SSEStream stream(final EventListener listener) { + + return SSEStream.create(httpClient,this,AccountResponse.class,listener); + } + + /** + * Build and execute request. Warning! {@link AccountResponse}s in {@link Page} will contain only keypair field. + * @return {@link Page} of {@link AccountResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + @Override + public AccountsRequestBuilder cursor(String token) { + super.cursor(token); + return this; + } + + @Override + public AccountsRequestBuilder limit(int number) { + super.limit(number); + return this; + } + + @Override + public AccountsRequestBuilder order(Order direction) { + super.order(direction); + return this; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/AssetsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/AssetsRequestBuilder.java new file mode 100644 index 0000000000..b91f793665 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/AssetsRequestBuilder.java @@ -0,0 +1,41 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.responses.Page; +import org.stellar.sdk.responses.AssetResponse; + +import java.io.IOException; + +public class AssetsRequestBuilder extends RequestBuilder { + public AssetsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "assets"); + } + + public AssetsRequestBuilder assetCode(String assetCode) { + uriBuilder.setQueryParameter("asset_code", assetCode); + return this; + } + + public AssetsRequestBuilder assetIssuer(String assetIssuer) { + uriBuilder.setQueryParameter("asset_issuer", assetIssuer); + return this; + } + + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/EffectsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/EffectsRequestBuilder.java new file mode 100644 index 0000000000..4d617f3c60 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/EffectsRequestBuilder.java @@ -0,0 +1,124 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.Page; +import org.stellar.sdk.responses.effects.EffectResponse; + +import java.io.IOException; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Builds requests connected to effects. + */ +public class EffectsRequestBuilder extends RequestBuilder { + public EffectsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "effects"); + } + + /** + * Builds request to GET /accounts/{account}/effects + * @see Effects for Account + * @param account Account for which to get effects + */ + public EffectsRequestBuilder forAccount(KeyPair account) { + account = checkNotNull(account, "account cannot be null"); + this.setSegments("accounts", account.getAccountId(), "effects"); + return this; + } + + /** + * Builds request to GET /ledgers/{ledgerSeq}/effects + * @see Effects for Ledger + * @param ledgerSeq Ledger for which to get effects + */ + public EffectsRequestBuilder forLedger(long ledgerSeq) { + this.setSegments("ledgers", String.valueOf(ledgerSeq), "effects"); + return this; + } + + /** + * Builds request to GET /transactions/{transactionId}/effects + * @see Effect for Transaction + * @param transactionId Transaction ID for which to get effects + */ + public EffectsRequestBuilder forTransaction(String transactionId) { + transactionId = checkNotNull(transactionId, "transactionId cannot be null"); + this.setSegments("transactions", transactionId, "effects"); + return this; + } + + /** + * Builds request to GET /operation/{operationId}/effects + * @see Effect for Operation + * @param operationId Operation ID for which to get effects + */ + public EffectsRequestBuilder forOperation(long operationId) { + this.setSegments("operations", String.valueOf(operationId), "effects"); + return this; + } + + /** + * Requests specific uri and returns {@link Page} of {@link EffectResponse}. + * This method is helpful for getting the next set of results. + * @return {@link Page} of {@link EffectResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Allows to stream SSE events from horizon. + * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events. + * This mode will keep the connection to horizon open and horizon will continue to return + * responses as ledgers close. + * @see Server-Sent Events + * @see Response Format documentation + * @param listener {@link EventListener} implementation with {@link EffectResponse} type + * @return EventSource object, so you can close() connection when not needed anymore + */ + public SSEStream stream(final EventListener listener) { + return SSEStream.create(httpClient,this,EffectResponse.class,listener); + } + + /** + * Build and execute request. + * @return {@link Page} of {@link EffectResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + @Override + public EffectsRequestBuilder cursor(String token) { + super.cursor(token); + return this; + } + + @Override + public EffectsRequestBuilder limit(int number) { + super.limit(number); + return this; + } + + @Override + public EffectsRequestBuilder order(Order direction) { + super.order(direction); + return this; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/ErrorResponse.java b/app/src/main/java/org/stellar/sdk/requests/ErrorResponse.java new file mode 100644 index 0000000000..4ee7517b57 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/ErrorResponse.java @@ -0,0 +1,23 @@ +package org.stellar.sdk.requests; + +/** + * Exception thrown when request returned an non-success HTTP code. + */ +public class ErrorResponse extends RuntimeException { + private int code; + private String body; + + public ErrorResponse(int code, String body) { + super("Error response from the server."); + this.code = code; + this.body = body; + } + + public int getCode() { + return code; + } + + public String getBody() { + return body; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/EventListener.java b/app/src/main/java/org/stellar/sdk/requests/EventListener.java new file mode 100644 index 0000000000..b926d6168a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/EventListener.java @@ -0,0 +1,12 @@ +package org.stellar.sdk.requests; + +/** + * This interface is used in {@link RequestBuilder} classes stream method. + */ +public interface EventListener { + /** + * This method will be called when new event is sent by a server. + * @param object object deserialized from the event data + */ + void onEvent(T object); +} diff --git a/app/src/main/java/org/stellar/sdk/requests/LedgersRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/LedgersRequestBuilder.java new file mode 100644 index 0000000000..e10ff0c5df --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/LedgersRequestBuilder.java @@ -0,0 +1,106 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.responses.LedgerResponse; +import org.stellar.sdk.responses.Page; + +import java.io.IOException; + +/** + * Builds requests connected to ledgers. + */ +public class LedgersRequestBuilder extends RequestBuilder { + public LedgersRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "ledgers"); + } + + /** + * Requests specific uri and returns {@link LedgerResponse}. + * This method is helpful for getting the links. + * @throws IOException + */ + public LedgerResponse ledger(HttpUrl uri) throws IOException { + TypeToken type = new TypeToken() {}; + ResponseHandler responseHandler = new ResponseHandler(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Requests GET /ledgers/{ledgerSeq} + * @see Ledger Details + * @param ledgerSeq Ledger to fetch + * @throws IOException + */ + public LedgerResponse ledger(long ledgerSeq) throws IOException { + this.setSegments("ledgers", String.valueOf(ledgerSeq)); + return this.ledger(this.buildUri()); + } + + /** + * Requests specific uri and returns {@link Page} of {@link LedgerResponse}. + * This method is helpful for getting the next set of results. + * @return {@link Page} of {@link LedgerResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Allows to stream SSE events from horizon. + * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events. + * This mode will keep the connection to horizon open and horizon will continue to return + * responses as ledgers close. + * @see Server-Sent Events + * @see Response Format documentation + * @param listener {@link EventListener} implementation with {@link LedgerResponse} type + * @return EventSource object, so you can close() connection when not needed anymore + */ + + public SSEStream stream(final EventListener listener) { + return SSEStream.create(httpClient,this,LedgerResponse.class,listener); + } + + /** + * Build and execute request. + * @return {@link Page} of {@link LedgerResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + @Override + public LedgersRequestBuilder cursor(String token) { + super.cursor(token); + return this; + } + + @Override + public LedgersRequestBuilder limit(int number) { + super.limit(number); + return this; + } + + @Override + public LedgersRequestBuilder order(Order direction) { + super.order(direction); + return this; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/OffersRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/OffersRequestBuilder.java new file mode 100644 index 0000000000..4438f7b8c3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/OffersRequestBuilder.java @@ -0,0 +1,81 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.OfferResponse; +import org.stellar.sdk.responses.Page; + +import java.io.IOException; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Builds requests connected to offers. + */ +public class OffersRequestBuilder extends RequestBuilder { + public OffersRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "offers"); + } + + /** + * Builds request to GET /accounts/{account}/offers + * @see Offers for Account + * @param account Account for which to get offers + */ + public OffersRequestBuilder forAccount(KeyPair account) { + account = checkNotNull(account, "account cannot be null"); + this.setSegments("accounts", account.getAccountId(), "offers"); + return this; + } + + /** + * Requests specific uri and returns {@link Page} of {@link OfferResponse}. + * This method is helpful for getting the next set of results. + * @return {@link Page} of {@link OfferResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + + + /** + * Build and execute request. + * @return {@link Page} of {@link OfferResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + @Override + public OffersRequestBuilder cursor(String token) { + super.cursor(token); + return this; + } + + @Override + public OffersRequestBuilder limit(int number) { + super.limit(number); + return this; + } + + @Override + public OffersRequestBuilder order(Order direction) { + super.order(direction); + return this; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/OperationFeeStatsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/OperationFeeStatsRequestBuilder.java new file mode 100644 index 0000000000..672a69aa7d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/OperationFeeStatsRequestBuilder.java @@ -0,0 +1,32 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.responses.OperationFeeStatsResponse; + +import java.io.IOException; + +public class OperationFeeStatsRequestBuilder extends RequestBuilder { + public OperationFeeStatsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "operation_fee_stats"); + } + + /** + * Requests GET /operation_fee_stats + * @see Operation Fee Stats + * @throws IOException + * @throws TooManyRequestsException + */ + public OperationFeeStatsResponse execute() throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken() {}; + ResponseHandler responseHandler = new ResponseHandler(type); + + Request request = new Request.Builder().get().url(this.buildUri()).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/OperationsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/OperationsRequestBuilder.java new file mode 100644 index 0000000000..f25acf5356 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/OperationsRequestBuilder.java @@ -0,0 +1,140 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.Page; +import org.stellar.sdk.responses.operations.OperationResponse; + +import java.io.IOException; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Builds requests connected to operations. + */ +public class OperationsRequestBuilder extends RequestBuilder { + public OperationsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "operations"); + } + + /** + * Requests specific uri and returns {@link OperationResponse}. + * This method is helpful for getting the links. + * @throws IOException + */ + public OperationResponse operation(HttpUrl uri) throws IOException { + TypeToken type = new TypeToken() {}; + ResponseHandler responseHandler = new ResponseHandler(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Requests GET /operations/{operationId} + * @see Operation Details + * @param operationId Operation to fetch + * @throws IOException + */ + public OperationResponse operation(long operationId) throws IOException { + this.setSegments("operation", String.valueOf(operationId)); + return this.operation(this.buildUri()); + } + + /** + * Builds request to GET /accounts/{account}/operations + * @see Operations for Account + * @param account Account for which to get operations + */ + public OperationsRequestBuilder forAccount(KeyPair account) { + account = checkNotNull(account, "account cannot be null"); + this.setSegments("accounts", account.getAccountId(), "operations"); + return this; + } + + /** + * Builds request to GET /ledgers/{ledgerSeq}/operations + * @see Operations for Ledger + * @param ledgerSeq Ledger for which to get operations + */ + public OperationsRequestBuilder forLedger(long ledgerSeq) { + this.setSegments("ledgers", String.valueOf(ledgerSeq), "operations"); + return this; + } + + /** + * Builds request to GET /transactions/{transactionId}/operations + * @see Operations for Transaction + * @param transactionId Transaction ID for which to get operations + */ + public OperationsRequestBuilder forTransaction(String transactionId) { + transactionId = checkNotNull(transactionId, "transactionId cannot be null"); + this.setSegments("transactions", transactionId, "operations"); + return this; + } + + /** + * Requests specific uri and returns {@link Page} of {@link OperationResponse}. + * This method is helpful for getting the next set of results. + * @return {@link Page} of {@link OperationResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Allows to stream SSE events from horizon. + * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events. + * This mode will keep the connection to horizon open and horizon will continue to return + * responses as ledgers close. + * @see Server-Sent Events + * @see Response Format documentation + * @param listener {@link OperationResponse} implementation with {@link OperationResponse} type + * @return EventSource object, so you can close() connection when not needed anymore + */ + public SSEStream stream(final EventListener listener) { + return SSEStream.create(httpClient,this,OperationResponse.class,listener); + } + + /** + * Build and execute request. + * @return {@link Page} of {@link OperationResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + @Override + public OperationsRequestBuilder cursor(String token) { + super.cursor(token); + return this; + } + + @Override + public OperationsRequestBuilder limit(int number) { + super.limit(number); + return this; + } + + @Override + public OperationsRequestBuilder order(Order direction) { + super.order(direction); + return this; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/OrderBookRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/OrderBookRequestBuilder.java new file mode 100644 index 0000000000..52d49c5c76 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/OrderBookRequestBuilder.java @@ -0,0 +1,79 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeCreditAlphaNum; +import org.stellar.sdk.responses.OrderBookResponse; + +import java.io.IOException; + +/** + * Builds requests connected to order book. + */ +public class OrderBookRequestBuilder extends RequestBuilder { + public OrderBookRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "order_book"); + } + + public OrderBookRequestBuilder buyingAsset(Asset asset) { + uriBuilder.setQueryParameter("buying_asset_type", asset.getType()); + if (asset instanceof AssetTypeCreditAlphaNum) { + AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset; + uriBuilder.setQueryParameter("buying_asset_code", creditAlphaNumAsset.getCode()); + uriBuilder.setQueryParameter("buying_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId()); + } + return this; + } + + public OrderBookRequestBuilder sellingAsset(Asset asset) { + uriBuilder.setQueryParameter("selling_asset_type", asset.getType()); + if (asset instanceof AssetTypeCreditAlphaNum) { + AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset; + uriBuilder.setQueryParameter("selling_asset_code", creditAlphaNumAsset.getCode()); + uriBuilder.setQueryParameter("selling_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId()); + } + return this; + } + + public static OrderBookResponse execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken() {}; + ResponseHandler responseHandler = new ResponseHandler(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Allows to stream SSE events from horizon. + * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events. + * This mode will keep the connection to horizon open and horizon will continue to return + * responses as ledgers close. + * @see Server-Sent Events + * @see Response Format documentation + * @param listener {@link OrderBookResponse} implementation with {@link OrderBookResponse} type + * @return EventSource object, so you can close() connection when not needed anymore + */ + public SSEStream stream(final EventListener listener) { + return SSEStream.create(httpClient,this,OrderBookResponse.class,listener); + } + + public OrderBookResponse execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + @Override + public RequestBuilder cursor(String cursor) { + throw new RuntimeException("Not implemented yet."); + } + + @Override + public RequestBuilder order(Order direction) { + throw new RuntimeException("Not implemented yet."); + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/PathsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/PathsRequestBuilder.java new file mode 100644 index 0000000000..c5927b36d8 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/PathsRequestBuilder.java @@ -0,0 +1,71 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; + +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeCreditAlphaNum; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.Page; +import org.stellar.sdk.responses.PathResponse; + +import java.io.IOException; + +/** + * Builds requests connected to paths. + */ +public class PathsRequestBuilder extends RequestBuilder { + public PathsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "paths"); + } + + public PathsRequestBuilder destinationAccount(KeyPair account) { + uriBuilder.setQueryParameter("destination_account", account.getAccountId()); + return this; + } + + public PathsRequestBuilder sourceAccount(KeyPair account) { + uriBuilder.setQueryParameter("source_account", account.getAccountId()); + return this; + } + + public PathsRequestBuilder destinationAmount(String amount) { + uriBuilder.setQueryParameter("destination_amount", amount); + return this; + } + + public PathsRequestBuilder destinationAsset(Asset asset) { + uriBuilder.setQueryParameter("destination_asset_type", asset.getType()); + if (asset instanceof AssetTypeCreditAlphaNum) { + AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset; + uriBuilder.setQueryParameter("destination_asset_code", creditAlphaNumAsset.getCode()); + uriBuilder.setQueryParameter("destination_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId()); + } + return this; + } + + /** + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/PaymentsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/PaymentsRequestBuilder.java new file mode 100644 index 0000000000..efe7ca7a98 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/PaymentsRequestBuilder.java @@ -0,0 +1,114 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.Page; +import org.stellar.sdk.responses.operations.OperationResponse; + +import java.io.IOException; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Builds requests connected to payments. + */ +public class PaymentsRequestBuilder extends RequestBuilder { + public PaymentsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "payments"); + } + + /** + * Builds request to GET /accounts/{account}/payments + * @see Payments for Account + * @param account Account for which to get payments + */ + public PaymentsRequestBuilder forAccount(KeyPair account) { + account = checkNotNull(account, "account cannot be null"); + this.setSegments("accounts", account.getAccountId(), "payments"); + return this; + } + + /** + * Builds request to GET /ledgers/{ledgerSeq}/payments + * @see Payments for Ledger + * @param ledgerSeq Ledger for which to get payments + */ + public PaymentsRequestBuilder forLedger(long ledgerSeq) { + this.setSegments("ledgers", String.valueOf(ledgerSeq), "payments"); + return this; + } + + /** + * Builds request to GET /transactions/{transactionId}/payments + * @see Payments for Transaction + * @param transactionId Transaction ID for which to get payments + */ + public PaymentsRequestBuilder forTransaction(String transactionId) { + transactionId = checkNotNull(transactionId, "transactionId cannot be null"); + this.setSegments("transactions", transactionId, "payments"); + return this; + } + + /** + * Requests specific uri and returns {@link Page} of {@link OperationResponse}. + * This method is helpful for getting the next set of results. + * @return {@link Page} of {@link OperationResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Allows to stream SSE events from horizon. + * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events. + * This mode will keep the connection to horizon open and horizon will continue to return + * responses as ledgers close. + * @see Server-Sent Events + * @see Response Format documentation + * @param listener {@link EventListener} implementation with {@link OperationResponse} type + * @return EventSource object, so you can close() connection when not needed anymore + */ + public SSEStream stream(final EventListener listener) { + return SSEStream.create(httpClient,this,OperationResponse.class,listener); + } + + /** + * Build and execute request. + * @return {@link Page} of {@link OperationResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + @Override + public PaymentsRequestBuilder cursor(String token) { + super.cursor(token); + return this; + } + + @Override + public PaymentsRequestBuilder limit(int number) { + super.limit(number); + return this; + } + + @Override + public PaymentsRequestBuilder order(Order direction) { + super.order(direction); + return this; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/RequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/RequestBuilder.java new file mode 100644 index 0000000000..5ae26a6331 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/RequestBuilder.java @@ -0,0 +1,97 @@ +package org.stellar.sdk.requests; + +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; + +import java.util.ArrayList; + +/** + * Abstract class for request builders. + */ +public abstract class RequestBuilder { + protected HttpUrl.Builder uriBuilder; + protected OkHttpClient httpClient; + private ArrayList segments; + private boolean segmentsAdded; + + RequestBuilder(OkHttpClient httpClient, HttpUrl serverURI, String defaultSegment) { + this.httpClient = httpClient; + uriBuilder = serverURI.newBuilder(); + segments = new ArrayList(); + if (defaultSegment != null) { + this.setSegments(defaultSegment); + } + segmentsAdded = false; // Allow overwriting segments + } + + protected RequestBuilder setSegments(String... segments) { + if (segmentsAdded) { + throw new RuntimeException("URL segments have been already added."); + } + + segmentsAdded = true; + // Remove default segments + this.segments.clear(); + for (String segment : segments) { + this.segments.add(segment); + } + + return this; + } + + /** + * Sets cursor parameter on the request. + * A cursor is a value that points to a specific location in a collection of resources. + * The cursor attribute itself is an opaque value meaning that users should not try to parse it. + * @see Page documentation + * @param cursor + */ + public RequestBuilder cursor(String cursor) { + uriBuilder.setQueryParameter("cursor", cursor); + return this; + } + + /** + * Sets limit parameter on the request. + * It defines maximum number of records to return. + * For range and default values check documentation of the endpoint requested. + * @param number maxium number of records to return + */ + public RequestBuilder limit(int number) { + uriBuilder.setQueryParameter("limit", String.valueOf(number)); + return this; + } + + /** + * Sets order parameter on the request. + * @param direction {@link org.stellar.sdk.requests.RequestBuilder.Order} + */ + public RequestBuilder order(Order direction) { + uriBuilder.setQueryParameter("order", direction.getValue()); + return this; + } + + HttpUrl buildUri() { + if (segments.size() > 0) { + for (String segment : segments) { + uriBuilder.addPathSegment(segment); + } + } + return uriBuilder.build(); + } + + /** + * Represents possible order parameter values. + */ + public enum Order { + ASC("asc"), + DESC("desc"); + private final String value; + Order(String value) { + this.value = value; + } + public String getValue() { + return value; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/ResponseHandler.java b/app/src/main/java/org/stellar/sdk/requests/ResponseHandler.java new file mode 100644 index 0000000000..c26a5fc67d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/ResponseHandler.java @@ -0,0 +1,54 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; + +import org.stellar.sdk.responses.GsonSingleton; +import org.stellar.sdk.responses.TypedResponse; + +import java.io.IOException; + +import okhttp3.Response; + +public class ResponseHandler { + + private TypeToken type; + + /** + * "Generics on a type are typically erased at runtime, except when the type is compiled with the + * generic parameter bound. In that case, the compiler inserts the generic type information into + * the compiled class. In other cases, that is not possible." + * More info: http://stackoverflow.com/a/14506181 + * @param type + */ + public ResponseHandler(TypeToken type) { + this.type = type; + } + + public T handleResponse(final Response response) throws IOException, TooManyRequestsException { + try { + // Too Many Requests + if (response.code() == 429) { + int retryAfter = Integer.parseInt(response.header("Retry-After")); + throw new TooManyRequestsException(retryAfter); + } + + String content = response.body().string(); + + // Other errors + if (response.code() >= 300) { + throw new ErrorResponse(response.code(), content); + } + + T object = GsonSingleton.getInstance().fromJson(content, type.getType()); + if (object instanceof org.stellar.sdk.responses.Response) { + ((org.stellar.sdk.responses.Response) object).setHeaders(response.headers()); + } + if(object instanceof TypedResponse) { + ((TypedResponse) object).setType(type); + } + return object; + } finally { + response.close(); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/SSEStream.java b/app/src/main/java/org/stellar/sdk/requests/SSEStream.java new file mode 100644 index 0000000000..b3c4abd763 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/SSEStream.java @@ -0,0 +1,195 @@ +package org.stellar.sdk.requests; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.internal.sse.RealEventSource; +import okhttp3.sse.EventSource; +import okhttp3.sse.EventSourceListener; +import org.stellar.sdk.responses.GsonSingleton; + +import javax.annotation.Nullable; +import java.io.Closeable; +import java.net.SocketException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + + +public class SSEStream implements Closeable { + private final OkHttpClient okHttpClient; + private final RequestBuilder requestBuilder; + private final Class responseClass; + private final EventListener listener; + + private final AtomicBoolean isStopped = new AtomicBoolean(false); + private final AtomicBoolean serverSideClosed = new AtomicBoolean(true); // make sure we start correctly + private final AtomicReference lastEventId = new AtomicReference(null); + private ExecutorService executorService; + private EventSource eventSource = null; + private final Lock lock = new ReentrantLock(); + + private SSEStream(final OkHttpClient okHttpClient, final RequestBuilder requestBuilder, final Class responseClass, final EventListener listener) { + // Create a new client with no read timeout + this.okHttpClient = okHttpClient.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); + this.requestBuilder = requestBuilder; + this.responseClass = responseClass; + this.listener = listener; + + + executorService = Executors.newSingleThreadExecutor(); + requestBuilder.buildUri(); // call this once to add the segments + } + + private void start() { + if (isStopped.get()) { + throw new IllegalStateException("Already stopped"); + } + executorService.submit(new Runnable() { + @Override + public void run() { + while (!isStopped.get()) { + try { + Thread.sleep(200); + if (serverSideClosed.get()) { + // don't restart until true again + serverSideClosed.set(false); + if (!isStopped.get()) { + lock.lock(); + try { + // check again if somebody called close in between + if (!isStopped.get()) { + restart(); + } + } finally { + lock.unlock(); + } + } + } + } catch (InterruptedException e) { + throw new IllegalStateException("interrupted", e); + } + } + } + }); + } + + public String lastPagingToken() { + return lastEventId.get(); + } + + private void restart() { + eventSource = doStreamRequest(this,okHttpClient, requestBuilder, responseClass, listener, requestBuilder.uriBuilder.build().toString(), new CloseListener() { + @Override + public void closed(EventSource source) { + serverSideClosed.set(true); + } + }); + } + + + public void close() { + isStopped.set(true); + if (eventSource != null) { + eventSource.cancel(); + } executorService.shutdownNow(); + } + + static SSEStream create( + final OkHttpClient okHttpClient, + final RequestBuilder requestBuilder, + final Class responseClass, + final EventListener listener) { + SSEStream stream = new SSEStream(okHttpClient, requestBuilder, responseClass, listener); + stream.start(); + return stream; + } + + private static EventSource doStreamRequest( + final SSEStream stream, + final OkHttpClient okHttpClient, + final RequestBuilder requestBuilder, + final Class responseClass, + final EventListener listener, + String url, + final CloseListener closeListener) { + + Request.Builder builder = new Request.Builder() + .url(url) + .header("Accept", "text/event-stream"); + String lastEventId = stream.lastEventId.get(); + if(lastEventId != null) { + builder.header("Last-Event-ID", lastEventId); + } + Request request = builder + .build(); + RealEventSource eventSource = new RealEventSource(request, new StellarEventSourceListener(stream,closeListener, responseClass, requestBuilder, listener)); + eventSource.connect(okHttpClient); + return eventSource; + } + + private interface CloseListener { + void closed(EventSource source); + } + + private static class StellarEventSourceListener extends EventSourceListener { + + private SSEStream stream; + private final CloseListener closeListener; + private final Class responseClass; + private final RequestBuilder requestBuilder; + private final EventListener listener; + + StellarEventSourceListener(SSEStream stream, CloseListener closeListener, Class responseClass, RequestBuilder requestBuilder, EventListener listener) { + this.stream = stream; + this.closeListener = closeListener; + this.responseClass = responseClass; + this.requestBuilder = requestBuilder; + this.listener = listener; + } + + @Override + public void onClosed(EventSource eventSource) { + if (closeListener != null) { + closeListener.closed(eventSource); + } + } + + @Override + public void onOpen(EventSource eventSource, Response response) { + } + + @Override + public void onFailure(EventSource eventSource, @Nullable Throwable t, @Nullable Response response) { + int code = -1; + if (response != null) { + code = response.code(); + } + if (t != null) { + if (t instanceof SocketException) { + // not a failure, server disconnected + } else { + throw new IllegalStateException("Failed " + code, t); + } + } else { + throw new IllegalStateException("Failed " + code); + } + } + + @Override + public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) { + if (data.equals("\"hello\"") || data.equals("\"byebye\"")) { + return; + } + T event = GsonSingleton.getInstance().fromJson(data, responseClass); + String pagingToken = event.getPagingToken(); + requestBuilder.cursor(pagingToken); + stream.lastEventId.set(id); + listener.onEvent(event); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/TooManyRequestsException.java b/app/src/main/java/org/stellar/sdk/requests/TooManyRequestsException.java new file mode 100644 index 0000000000..4c23972216 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/TooManyRequestsException.java @@ -0,0 +1,21 @@ +package org.stellar.sdk.requests; + +/** + * Exception thrown when too many requests were sent to the Horizon server. + * @see Rate Limiting + */ +public class TooManyRequestsException extends RuntimeException { + private int retryAfter; + + public TooManyRequestsException(int retryAfter) { + super("The rate limit for the requesting IP address is over its alloted limit."); + this.retryAfter = retryAfter; + } + + /** + * Returns number of seconds a client should wait before sending requests again. + */ + public int getRetryAfter() { + return retryAfter; + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/TradeAggregationsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/TradeAggregationsRequestBuilder.java new file mode 100644 index 0000000000..58d5258fb7 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/TradeAggregationsRequestBuilder.java @@ -0,0 +1,61 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeCreditAlphaNum; +import org.stellar.sdk.responses.Page; +import org.stellar.sdk.responses.TradeAggregationResponse; + +import java.io.IOException; + +/** + * Builds requests connected to trades. + */ +public class TradeAggregationsRequestBuilder extends RequestBuilder { + public TradeAggregationsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI, Asset baseAsset, Asset counterAsset, long startTime, long endTime, long resolution, long offset) { + super(httpClient, serverURI, "trade_aggregations"); + + this.baseAsset(baseAsset); + this.counterAsset(counterAsset); + uriBuilder.setQueryParameter("start_time", String.valueOf(startTime)); + uriBuilder.setQueryParameter("end_time", String.valueOf(endTime)); + uriBuilder.setQueryParameter("resolution", String.valueOf(resolution)); + uriBuilder.setQueryParameter("offset", String.valueOf(offset)); + } + + private void baseAsset(Asset asset) { + uriBuilder.setQueryParameter("base_asset_type", asset.getType()); + if (asset instanceof AssetTypeCreditAlphaNum) { + AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset; + uriBuilder.setQueryParameter("base_asset_code", creditAlphaNumAsset.getCode()); + uriBuilder.setQueryParameter("base_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId()); + } + } + + private void counterAsset(Asset asset) { + uriBuilder.setQueryParameter("counter_asset_type", asset.getType()); + if (asset instanceof AssetTypeCreditAlphaNum) { + AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset; + uriBuilder.setQueryParameter("counter_asset_code", creditAlphaNumAsset.getCode()); + uriBuilder.setQueryParameter("counter_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId()); + } + } + + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/TradesRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/TradesRequestBuilder.java new file mode 100644 index 0000000000..53fbea5ade --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/TradesRequestBuilder.java @@ -0,0 +1,101 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import java.io.IOException; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeCreditAlphaNum; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.Page; +import org.stellar.sdk.responses.TradeResponse; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Builds requests connected to trades. + */ +public class TradesRequestBuilder extends RequestBuilder { + public TradesRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "trades"); + } + + public TradesRequestBuilder baseAsset(Asset asset) { + uriBuilder.setQueryParameter("base_asset_type", asset.getType()); + if (asset instanceof AssetTypeCreditAlphaNum) { + AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset; + uriBuilder.setQueryParameter("base_asset_code", creditAlphaNumAsset.getCode()); + uriBuilder.setQueryParameter("base_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId()); + } + return this; + } + + public TradesRequestBuilder counterAsset(Asset asset) { + uriBuilder.setQueryParameter("counter_asset_type", asset.getType()); + if (asset instanceof AssetTypeCreditAlphaNum) { + AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset; + uriBuilder.setQueryParameter("counter_asset_code", creditAlphaNumAsset.getCode()); + uriBuilder.setQueryParameter("counter_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId()); + } + return this; + } + + /** + * Builds request to GET /accounts/{account}/trades + * @see Trades for Account + * @param account Account for which to get trades + */ + public TradesRequestBuilder forAccount(KeyPair account) { + account = checkNotNull(account, "account cannot be null"); + this.setSegments("accounts", account.getAccountId(), "trades"); + return this; + } + + public static Page execute(OkHttpClient httpClient, HttpUrl uri) + throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>( + type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + return responseHandler.handleResponse(response); + } + + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + public TradesRequestBuilder offerId(String offerId) { + uriBuilder.setQueryParameter("offer_id", offerId); + return this; + } + + @Override + public TradesRequestBuilder cursor(String token) { + super.cursor(token); + return this; + } + + @Override + public TradesRequestBuilder limit(int number) { + super.limit(number); + return this; + } + + /** + * Allows to stream SSE events from horizon. + * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events. + * This mode will keep the connection to horizon open and horizon will continue to return + * responses as ledgers close. + * @see Server-Sent Events + * @see Response Format documentation + * @param listener {@link EventListener} implementation with {@link TradeResponse} type + * @return EventSource object, so you can close() connection when not needed anymore + */ + public SSEStream stream(final EventListener listener) { + return SSEStream.create(httpClient,this,TradeResponse.class,listener); + } +} diff --git a/app/src/main/java/org/stellar/sdk/requests/TransactionsRequestBuilder.java b/app/src/main/java/org/stellar/sdk/requests/TransactionsRequestBuilder.java new file mode 100644 index 0000000000..d0c2768e53 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/requests/TransactionsRequestBuilder.java @@ -0,0 +1,129 @@ +package org.stellar.sdk.requests; + +import com.google.gson.reflect.TypeToken; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.Page; +import org.stellar.sdk.responses.TransactionResponse; + +import java.io.IOException; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Builds requests connected to transactions. + */ +public class TransactionsRequestBuilder extends RequestBuilder { + public TransactionsRequestBuilder(OkHttpClient httpClient, HttpUrl serverURI) { + super(httpClient, serverURI, "transactions"); + } + + /** + * Requests specific uri and returns {@link TransactionResponse}. + * This method is helpful for getting the links. + * @throws IOException + */ + public TransactionResponse transaction(HttpUrl uri) throws IOException { + TypeToken type = new TypeToken() {}; + ResponseHandler responseHandler = new ResponseHandler(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Requests GET /transactions/{transactionId} + * @see Transaction Details + * @param transactionId Transaction to fetch + * @throws IOException + */ + public TransactionResponse transaction(String transactionId) throws IOException { + this.setSegments("transactions", transactionId); + return this.transaction(this.buildUri()); + } + + /** + * Builds request to GET /accounts/{account}/transactions + * @see Transactions for Account + * @param account Account for which to get transactions + */ + public TransactionsRequestBuilder forAccount(KeyPair account) { + account = checkNotNull(account, "account cannot be null"); + this.setSegments("accounts", account.getAccountId(), "transactions"); + return this; + } + + /** + * Builds request to GET /ledgers/{ledgerSeq}/transactions + * @see Transactions for Ledger + * @param ledgerSeq Ledger for which to get transactions + */ + public TransactionsRequestBuilder forLedger(long ledgerSeq) { + this.setSegments("ledgers", String.valueOf(ledgerSeq), "transactions"); + return this; + } + + /** + * Requests specific uri and returns {@link Page} of {@link TransactionResponse}. + * This method is helpful for getting the next set of results. + * @return {@link Page} of {@link TransactionResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public static Page execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException { + TypeToken type = new TypeToken>() {}; + ResponseHandler> responseHandler = new ResponseHandler>(type); + + Request request = new Request.Builder().get().url(uri).build(); + Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + /** + * Allows to stream SSE events from horizon. + * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events. + * This mode will keep the connection to horizon open and horizon will continue to return + * responses as ledgers close. + * @see Server-Sent Events + * @see Response Format documentation + * @param listener {@link EventListener} implementation with {@link TransactionResponse} type + * @return EventSource object, so you can close() connection when not needed anymore + */ + public SSEStream stream(final EventListener listener) { + return SSEStream.create(httpClient,this,TransactionResponse.class,listener); + } + + /** + * Build and execute request. + * @return {@link Page} of {@link TransactionResponse} + * @throws TooManyRequestsException when too many requests were sent to the Horizon server. + * @throws IOException + */ + public Page execute() throws IOException, TooManyRequestsException { + return this.execute(this.httpClient, this.buildUri()); + } + + @Override + public TransactionsRequestBuilder cursor(String token) { + super.cursor(token); + return this; + } + + @Override + public TransactionsRequestBuilder limit(int number) { + super.limit(number); + return this; + } + + @Override + public TransactionsRequestBuilder order(Order direction) { + super.order(direction); + return this; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/AccountResponse.java b/app/src/main/java/org/stellar/sdk/responses/AccountResponse.java new file mode 100644 index 0000000000..60e27fb05d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/AccountResponse.java @@ -0,0 +1,351 @@ +package org.stellar.sdk.responses; + +import com.google.common.io.BaseEncoding; +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +import java.util.HashMap; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents account response. + * @see Account documentation + * @see org.stellar.sdk.requests.AccountsRequestBuilder + * @see org.stellar.sdk.Server#accounts() + */ +public class AccountResponse extends Response implements org.stellar.sdk.TransactionBuilderAccount { + @SerializedName("account_id") /* KeyPairTypeAdapter used */ + private KeyPair keypair; + @SerializedName("sequence") + private Long sequenceNumber; + @SerializedName("paging_token") + private String pagingToken; + @SerializedName("subentry_count") + private Integer subentryCount; + @SerializedName("inflation_destination") + private String inflationDestination; + @SerializedName("home_domain") + private String homeDomain; + @SerializedName("thresholds") + private Thresholds thresholds; + @SerializedName("flags") + private Flags flags; + @SerializedName("balances") + private Balance[] balances; + @SerializedName("signers") + private Signer[] signers; + @SerializedName("data") + private Data data; + @SerializedName("_links") + private Links links; + + AccountResponse(KeyPair keypair) { + this.keypair = keypair; + } + + public AccountResponse(KeyPair keypair, Long sequenceNumber) { + this.keypair = keypair; + this.sequenceNumber = sequenceNumber; + } + + @Override + public KeyPair getKeypair() { + return keypair; + } + + @Override + public Long getSequenceNumber() { + return sequenceNumber; + } + + @Override + public Long getIncrementedSequenceNumber() { + return new Long(sequenceNumber + 1); + } + + @Override + public void incrementSequenceNumber() { + sequenceNumber++; + } + + public String getPagingToken() { + return pagingToken; + } + + public Integer getSubentryCount() { + return subentryCount; + } + + public String getInflationDestination() { + return inflationDestination; + } + + public String getHomeDomain() { + return homeDomain; + } + + public Thresholds getThresholds() { + return thresholds; + } + + public Flags getFlags() { + return flags; + } + + public Balance[] getBalances() { + return balances; + } + + public Signer[] getSigners() { + return signers; + } + + public Data getData() { + return data; + } + + /** + * Represents account thresholds. + */ + public static class Thresholds { + @SerializedName("low_threshold") + private final int lowThreshold; + @SerializedName("med_threshold") + private final int medThreshold; + @SerializedName("high_threshold") + private final int highThreshold; + + Thresholds(int lowThreshold, int medThreshold, int highThreshold) { + this.lowThreshold = lowThreshold; + this.medThreshold = medThreshold; + this.highThreshold = highThreshold; + } + + public int getLowThreshold() { + return lowThreshold; + } + + public int getMedThreshold() { + return medThreshold; + } + + public int getHighThreshold() { + return highThreshold; + } + } + + /** + * Represents account flags. + */ + public static class Flags { + @SerializedName("auth_required") + private final boolean authRequired; + @SerializedName("auth_revocable") + private final boolean authRevocable; + @SerializedName("auth_immutable") + private final boolean authImmutable; + + Flags(boolean authRequired, boolean authRevocable, boolean authImmutable) { + this.authRequired = authRequired; + this.authRevocable = authRevocable; + this.authImmutable = authImmutable; + } + + public boolean getAuthRequired() { + return authRequired; + } + + public boolean getAuthRevocable() { + return authRevocable; + } + + public boolean getAuthImmutable() { + return authImmutable; + } + } + + /** + * Represents account balance. + */ + public static class Balance { + @SerializedName("asset_type") + private final String assetType; + @SerializedName("asset_code") + private final String assetCode; + @SerializedName("asset_issuer") + private final String assetIssuer; + @SerializedName("limit") + private final String limit; + @SerializedName("balance") + private final String balance; + @SerializedName("buying_liabilities") + private final String buyingLiabilities; + @SerializedName("selling_liabilities") + private final String sellingLiabilities; + + Balance(String assetType, String assetCode, String assetIssuer, String balance, String limit, String buyingLiabilities, String sellingLiabilities) { + this.assetType = checkNotNull(assetType, "assertType cannot be null"); + this.balance = checkNotNull(balance, "balance cannot be null"); + this.limit = limit; + this.assetCode = assetCode; + this.assetIssuer = assetIssuer; + this.buyingLiabilities = checkNotNull(buyingLiabilities, "buyingLiabilities cannot be null"); + this.sellingLiabilities = checkNotNull(sellingLiabilities, "sellingLiabilities cannot be null"); + } + + public Asset getAsset() { + if (assetType.equals("native")) { + return new AssetTypeNative(); + } else { + return Asset.createNonNativeAsset(assetCode, getAssetIssuer()); + } + } + + public String getAssetType() { + return assetType; + } + + public String getAssetCode() { + return assetCode; + } + + public KeyPair getAssetIssuer() { + return KeyPair.fromAccountId(assetIssuer); + } + + public String getBalance() { + return balance; + } + + public String getBuyingLiabilities() { + return buyingLiabilities; + } + + public String getSellingLiabilities() { + return sellingLiabilities; + } + + public String getLimit() { + return limit; + } + } + + /** + * Represents account signers. + */ + public static class Signer { + @SerializedName("key") + private final String key; + @SerializedName("type") + private final String type; + @SerializedName("weight") + private final int weight; + + Signer(String key, String type, int weight) { + this.key = checkNotNull(key, "key cannot be null"); + this.type = checkNotNull(type, "type cannot be null"); + this.weight = checkNotNull(weight, "weight cannot be null"); + } + + /** + * @deprecated Use {@link Signer#getKey()} + * @return + */ + public String getAccountId() { + return key; + } + + public String getKey() { + return key; + } + + public int getWeight() { + return weight; + } + + public String getType() { + return type; + } + } + + public Links getLinks() { + return links; + } + + /** + * Data connected to account. + */ + public static class Data extends HashMap { + @Override + public int size() { + return super.size(); + } + + /** + * Gets base64-encoded value for a given key. + * @param key Data entry name + * @return base64-encoded value + */ + public String get(String key) { + return super.get(key); + } + + /** + * Gets raw value for a given key. + * @param key Data entry name + * @return raw value + */ + public byte[] getDecoded(String key) { + BaseEncoding base64Encoding = BaseEncoding.base64(); + return base64Encoding.decode(this.get(key)); + } + } + + /** + * Links connected to account. + */ + public static class Links { + @SerializedName("effects") + private final Link effects; + @SerializedName("offers") + private final Link offers; + @SerializedName("operations") + private final Link operations; + @SerializedName("self") + private final Link self; + @SerializedName("transactions") + private final Link transactions; + + Links(Link effects, Link offers, Link operations, Link self, Link transactions) { + this.effects = effects; + this.offers = offers; + this.operations = operations; + this.self = self; + this.transactions = transactions; + } + + public Link getEffects() { + return effects; + } + + public Link getOffers() { + return offers; + } + + public Link getOperations() { + return operations; + } + + public Link getSelf() { + return self; + } + + public Link getTransactions() { + return transactions; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/AssetDeserializer.java b/app/src/main/java/org/stellar/sdk/responses/AssetDeserializer.java new file mode 100644 index 0000000000..a811a72fb2 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/AssetDeserializer.java @@ -0,0 +1,26 @@ +package org.stellar.sdk.responses; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +import java.lang.reflect.Type; + +class AssetDeserializer implements JsonDeserializer { + @Override + public Asset deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + String type = json.getAsJsonObject().get("asset_type").getAsString(); + if (type.equals("native")) { + return new AssetTypeNative(); + } else { + String code = json.getAsJsonObject().get("asset_code").getAsString(); + String issuer = json.getAsJsonObject().get("asset_issuer").getAsString(); + return Asset.createNonNativeAsset(code, KeyPair.fromAccountId(issuer)); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/AssetResponse.java b/app/src/main/java/org/stellar/sdk/responses/AssetResponse.java new file mode 100644 index 0000000000..774eefc463 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/AssetResponse.java @@ -0,0 +1,109 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; +import org.stellar.sdk.Asset; + +public class AssetResponse extends Response { + @SerializedName("asset_type") + private final String assetType; + @SerializedName("asset_code") + private final String assetCode; + @SerializedName("asset_issuer") + private final String assetIssuer; + @SerializedName("paging_token") + private final String pagingToken; + @SerializedName("amount") + private final String amount; + @SerializedName("num_accounts") + private final int numAccounts; + @SerializedName("flags") + private final AssetResponse.Flags flags; + @SerializedName("_links") + private final AssetResponse.Links links; + + public AssetResponse(String assetType, String assetCode, String assetIssuer, String pagingToken, String amount, int numAccounts, Flags flags, Links links) { + this.assetType = assetType; + this.assetCode = assetCode; + this.assetIssuer = assetIssuer; + this.pagingToken = pagingToken; + this.amount = amount; + this.numAccounts = numAccounts; + this.flags = flags; + this.links = links; + } + + public String getAssetType() { + return assetType; + } + + public String getAssetCode() { + return assetCode; + } + + public String getAssetIssuer() { + return assetIssuer; + } + + public Asset getAsset() { + return Asset.create(this.assetType, this.assetCode, this.assetIssuer); + } + + public String getPagingToken() { + return pagingToken; + } + + public String getAmount() { + return amount; + } + + public int getNumAccounts() { + return numAccounts; + } + + public Flags getFlags() { + return flags; + } + + public Links getLinks() { + return links; + } + + /** + * Flags describe asset flags. + */ + public static class Flags { + @SerializedName("auth_required") + private final boolean authRequired; + @SerializedName("auth_revocable") + private final boolean authRevocable; + + public Flags(boolean authRequired, boolean authRevocable) { + this.authRequired = authRequired; + this.authRevocable = authRevocable; + } + + public boolean isAuthRequired() { + return authRequired; + } + + public boolean isAuthRevocable() { + return authRevocable; + } + } + + /** + * Links connected to asset. + */ + public static class Links { + @SerializedName("toml") + private final Link toml; + + public Links(Link toml) { + this.toml = toml; + } + + public Link getToml() { + return toml; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/EffectDeserializer.java b/app/src/main/java/org/stellar/sdk/responses/EffectDeserializer.java new file mode 100644 index 0000000000..0826d866fb --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/EffectDeserializer.java @@ -0,0 +1,83 @@ +package org.stellar.sdk.responses; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.effects.*; + +import java.lang.reflect.Type; + +class EffectDeserializer implements JsonDeserializer { + @Override + public EffectResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + // Create new Gson object with adapters needed in Operation + Gson gson = new GsonBuilder() + .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe()) + .create(); + + int type = json.getAsJsonObject().get("type_i").getAsInt(); + switch (type) { + // Account effects + case 0: + return gson.fromJson(json, AccountCreatedEffectResponse.class); + case 1: + return gson.fromJson(json, AccountRemovedEffectResponse.class); + case 2: + return gson.fromJson(json, AccountCreditedEffectResponse.class); + case 3: + return gson.fromJson(json, AccountDebitedEffectResponse.class); + case 4: + return gson.fromJson(json, AccountThresholdsUpdatedEffectResponse.class); + case 5: + return gson.fromJson(json, AccountHomeDomainUpdatedEffectResponse.class); + case 6: + return gson.fromJson(json, AccountFlagsUpdatedEffectResponse.class); + case 7: + return gson.fromJson(json, AccountInflationDestinationUpdatedEffectResponse.class); + // Signer effects + case 10: + return gson.fromJson(json, SignerCreatedEffectResponse.class); + case 11: + return gson.fromJson(json, SignerRemovedEffectResponse.class); + case 12: + return gson.fromJson(json, SignerUpdatedEffectResponse.class); + // Trustline effects + case 20: + return gson.fromJson(json, TrustlineCreatedEffectResponse.class); + case 21: + return gson.fromJson(json, TrustlineRemovedEffectResponse.class); + case 22: + return gson.fromJson(json, TrustlineUpdatedEffectResponse.class); + case 23: + return gson.fromJson(json, TrustlineAuthorizedEffectResponse.class); + case 24: + return gson.fromJson(json, TrustlineDeauthorizedEffectResponse.class); + // Trading effects + case 30: + return gson.fromJson(json, OfferCreatedEffectResponse.class); + case 31: + return gson.fromJson(json, OfferRemovedEffectResponse.class); + case 32: + return gson.fromJson(json, OfferUpdatedEffectResponse.class); + case 33: + return gson.fromJson(json, TradeEffectResponse.class); + // Data effects + case 40: + return gson.fromJson(json, DataCreatedEffectResponse.class); + case 41: + return gson.fromJson(json, DataRemovedEffectResponse.class); + case 42: + return gson.fromJson(json, DataUpdatedEffectResponse.class); + // Bump Sequence effects + case 43: + return gson.fromJson(json, SequenceBumpedEffectResponse.class); + default: + throw new RuntimeException("Invalid operation type"); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/GsonSingleton.java b/app/src/main/java/org/stellar/sdk/responses/GsonSingleton.java new file mode 100644 index 0000000000..49c9ab6462 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/GsonSingleton.java @@ -0,0 +1,51 @@ +package org.stellar.sdk.responses; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.effects.EffectResponse; +import org.stellar.sdk.responses.operations.OperationResponse; + +public class GsonSingleton { + private static Gson instance = null; + + protected GsonSingleton() {} + + public static Gson getInstance() { + if (instance == null) { + TypeToken accountPageType = new TypeToken>() {}; + TypeToken assetPageType = new TypeToken>() {}; + TypeToken effectPageType = new TypeToken>() {}; + TypeToken ledgerPageType = new TypeToken>() {}; + TypeToken offerPageType = new TypeToken>() {}; + TypeToken operationPageType = new TypeToken>() {}; + TypeToken pathPageType = new TypeToken>() {}; + TypeToken tradePageType = new TypeToken>() {}; + TypeToken tradeAggregationPageType = new TypeToken>() {}; + TypeToken transactionPageType = new TypeToken>() {}; + + instance = new GsonBuilder() + .registerTypeAdapter(Asset.class, new AssetDeserializer()) + .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe()) + .registerTypeAdapter(OperationResponse.class, new OperationDeserializer()) + .registerTypeAdapter(EffectResponse.class, new EffectDeserializer()) + .registerTypeAdapter(TransactionResponse.class, new TransactionDeserializer()) + .registerTypeAdapter(accountPageType.getType(), new PageDeserializer(accountPageType)) + .registerTypeAdapter(assetPageType.getType(), new PageDeserializer(assetPageType)) + .registerTypeAdapter(effectPageType.getType(), new PageDeserializer(effectPageType)) + .registerTypeAdapter(ledgerPageType.getType(), new PageDeserializer(ledgerPageType)) + .registerTypeAdapter(offerPageType.getType(), new PageDeserializer(offerPageType)) + .registerTypeAdapter(operationPageType.getType(), new PageDeserializer(operationPageType)) + .registerTypeAdapter(pathPageType.getType(), new PageDeserializer(pathPageType)) + .registerTypeAdapter(tradePageType.getType(), new PageDeserializer(tradePageType)) + .registerTypeAdapter(tradeAggregationPageType.getType(), new PageDeserializer(tradeAggregationPageType)) + .registerTypeAdapter(transactionPageType.getType(), new PageDeserializer(transactionPageType)) + .create(); + } + return instance; + } + +} diff --git a/app/src/main/java/org/stellar/sdk/responses/KeyPairTypeAdapter.java b/app/src/main/java/org/stellar/sdk/responses/KeyPairTypeAdapter.java new file mode 100644 index 0000000000..4d25162a96 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/KeyPairTypeAdapter.java @@ -0,0 +1,21 @@ +package org.stellar.sdk.responses; + +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import org.stellar.sdk.KeyPair; + +import java.io.IOException; + +class KeyPairTypeAdapter extends TypeAdapter { + @Override + public void write(JsonWriter out, KeyPair value) throws IOException { + // Don't need this. + } + + @Override + public KeyPair read(JsonReader in) throws IOException { + return KeyPair.fromAccountId(in.nextString()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/LedgerResponse.java b/app/src/main/java/org/stellar/sdk/responses/LedgerResponse.java new file mode 100644 index 0000000000..aee4602ce5 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/LedgerResponse.java @@ -0,0 +1,171 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents ledger response. + * @see Ledger documentation + * @see org.stellar.sdk.requests.LedgersRequestBuilder + * @see org.stellar.sdk.Server#ledgers() + */ +public class LedgerResponse extends Response { + @SerializedName("sequence") + private final Long sequence; + @SerializedName("hash") + private final String hash; + @SerializedName("paging_token") + private final String pagingToken; + @SerializedName("prev_hash") + private final String prevHash; + @SerializedName("transaction_count") + private final Integer transactionCount; + @SerializedName("operation_count") + private final Integer operationCount; + @SerializedName("closed_at") + private final String closedAt; + @SerializedName("total_coins") + private final String totalCoins; + @SerializedName("fee_pool") + private final String feePool; + @SerializedName("base_fee") + private final Long baseFee; + @SerializedName("base_reserve") + private final String baseReserve; + @SerializedName("base_fee_in_stroops") + private final String baseFeeInStroops; + @SerializedName("base_reserve_in_stroops") + private final String baseReserveInStroops; + @SerializedName("max_tx_set_size") + private final Integer maxTxSetSize; + @SerializedName("protocol_version") + private final Integer protocolVersion; + @SerializedName("header_xdr") + private final String headerXdr; + @SerializedName("_links") + private final Links links; + + LedgerResponse(Long sequence, String hash, String pagingToken, String prevHash, Integer transactionCount, Integer operationCount, String closedAt, String totalCoins, String feePool, Long baseFee, String baseReserve, String baseFeeInStroops, String baseReserveInStroops, Integer maxTxSetSize, Integer protocolVersion, String headerXdr, Links links) { + this.sequence = sequence; + this.hash = hash; + this.pagingToken = pagingToken; + this.prevHash = prevHash; + this.transactionCount = transactionCount; + this.operationCount = operationCount; + this.closedAt = closedAt; + this.totalCoins = totalCoins; + this.feePool = feePool; + this.baseFee = baseFee; + this.baseFeeInStroops = baseFeeInStroops; + this.baseReserve = baseReserve; + this.baseReserveInStroops = baseReserveInStroops; + this.maxTxSetSize = maxTxSetSize; + this.protocolVersion = protocolVersion; + this.headerXdr = headerXdr; + this.links = links; + } + + public Long getSequence() { + return sequence; + } + + public String getHash() { + return hash; + } + + public String getPagingToken() { + return pagingToken; + } + + public String getPrevHash() { + return prevHash; + } + + public Integer getTransactionCount() { + return transactionCount; + } + + public Integer getOperationCount() { + return operationCount; + } + + public String getClosedAt() { + return closedAt; + } + + public String getTotalCoins() { + return totalCoins; + } + + public String getFeePool() { + return feePool; + } + + public Long getBaseFee() { + return baseFee; + } + + public String getBaseReserve() { + return baseReserve; + } + + public String getBaseFeeInStroops() { + return baseFeeInStroops; + } + + public String getBaseReserveInStroops() { + return baseReserveInStroops; + } + + public Integer getMaxTxSetSize() { + return maxTxSetSize; + } + + public Integer getProtocolVersion() { + return protocolVersion; + } + + public String getHeaderXdr() { + return headerXdr; + } + + public Links getLinks() { + return links; + } + + /** + * Links connected to ledger. + */ + public static class Links { + @SerializedName("effects") + private final Link effects; + @SerializedName("operations") + private final Link operations; + @SerializedName("self") + private final Link self; + @SerializedName("transactions") + private final Link transactions; + + Links(Link effects, Link operations, Link self, Link transactions) { + this.effects = effects; + this.operations = operations; + this.self = self; + this.transactions = transactions; + } + + public Link getEffects() { + return effects; + } + + public Link getOperations() { + return operations; + } + + public Link getSelf() { + return self; + } + + public Link getTransactions() { + return transactions; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/Link.java b/app/src/main/java/org/stellar/sdk/responses/Link.java new file mode 100644 index 0000000000..b69a22ba73 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/Link.java @@ -0,0 +1,39 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; + +import java.net.URI; +import java.net.URISyntaxException; + +/** + * Represents links in responses. + */ +public class Link { + @SerializedName("href") + private final String href; + @SerializedName("templated") + private final boolean templated; + + Link(String href, boolean templated) { + this.href = href; + this.templated = templated; + } + + public String getHref() { + // TODO templated + return href; + } + + public URI getUri() { + // TODO templated + try { + return new URI(href); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + public boolean isTemplated() { + return templated; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/OfferResponse.java b/app/src/main/java/org/stellar/sdk/responses/OfferResponse.java new file mode 100644 index 0000000000..aa4c6b88b2 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/OfferResponse.java @@ -0,0 +1,97 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.KeyPair; + +/** + * Represents offer response. + * @see Offer documentation + * @see org.stellar.sdk.requests.OffersRequestBuilder + * @see org.stellar.sdk.Server#offers() + */ +public class OfferResponse extends Response { + @SerializedName("id") + private final Long id; + @SerializedName("paging_token") + private final String pagingToken; + @SerializedName("seller") + private final KeyPair seller; + @SerializedName("selling") + private final Asset selling; + @SerializedName("buying") + private final Asset buying; + @SerializedName("amount") + private final String amount; + @SerializedName("price") + private final String price; + @SerializedName("_links") + private final Links links; + + OfferResponse(Long id, String pagingToken, KeyPair seller, Asset selling, Asset buying, String amount, String price, Links links) { + this.id = id; + this.pagingToken = pagingToken; + this.seller = seller; + this.selling = selling; + this.buying = buying; + this.amount = amount; + this.price = price; + this.links = links; + } + + public Long getId() { + return id; + } + + public String getPagingToken() { + return pagingToken; + } + + public KeyPair getSeller() { + return seller; + } + + public Asset getSelling() { + return selling; + } + + public Asset getBuying() { + return buying; + } + + public String getAmount() { + return amount; + } + + public String getPrice() { + return price; + } + + public Links getLinks() { + return links; + } + + /** + * Links connected to ledger. + */ + public static class Links { + @SerializedName("self") + private final Link self; + @SerializedName("offer_maker") + private final Link offerMaker; + + public Links(Link self, Link offerMaker) { + this.self = self; + this.offerMaker = offerMaker; + } + + public Link getSelf() { + return self; + } + + public Link getOfferMaker() { + return offerMaker; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/OperationDeserializer.java b/app/src/main/java/org/stellar/sdk/responses/OperationDeserializer.java new file mode 100644 index 0000000000..973b5d7a28 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/OperationDeserializer.java @@ -0,0 +1,53 @@ +package org.stellar.sdk.responses; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.operations.*; + +import java.lang.reflect.Type; + +class OperationDeserializer implements JsonDeserializer { + @Override + public OperationResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + // Create new Gson object with adapters needed in Operation + Gson gson = new GsonBuilder() + .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe()) + .create(); + + int type = json.getAsJsonObject().get("type_i").getAsInt(); + switch (type) { + case 0: + return gson.fromJson(json, CreateAccountOperationResponse.class); + case 1: + return gson.fromJson(json, PaymentOperationResponse.class); + case 2: + return gson.fromJson(json, PathPaymentOperationResponse.class); + case 3: + return gson.fromJson(json, ManageOfferOperationResponse.class); + case 4: + return gson.fromJson(json, CreatePassiveOfferOperationResponse.class); + case 5: + return gson.fromJson(json, SetOptionsOperationResponse.class); + case 6: + return gson.fromJson(json, ChangeTrustOperationResponse.class); + case 7: + return gson.fromJson(json, AllowTrustOperationResponse.class); + case 8: + return gson.fromJson(json, AccountMergeOperationResponse.class); + case 9: + return gson.fromJson(json, InflationOperationResponse.class); + case 10: + return gson.fromJson(json, ManageDataOperationResponse.class); + case 11: + return gson.fromJson(json, BumpSequenceOperationResponse.class); + default: + throw new RuntimeException("Invalid operation type"); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/OperationFeeStatsResponse.java b/app/src/main/java/org/stellar/sdk/responses/OperationFeeStatsResponse.java new file mode 100644 index 0000000000..f58cbebe3e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/OperationFeeStatsResponse.java @@ -0,0 +1,37 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; + +public class OperationFeeStatsResponse extends Response { + @SerializedName("min_accepted_fee") + private final Long min; + @SerializedName("mode_accepted_fee") + private final Long mode; + @SerializedName("last_ledger_base_fee") + private final Long lastLedgerBaseFee; + @SerializedName("last_ledger") + private final Long lastLedger; + + public OperationFeeStatsResponse(Long min, Long mode, Long lastLedgerBaseFee, Long lastLedger) { + this.min = min; + this.mode = mode; + this.lastLedgerBaseFee = lastLedgerBaseFee; + this.lastLedger = lastLedger; + } + + public Long getMin() { + return min; + } + + public Long getMode() { + return mode; + } + + public Long getLastLedgerBaseFee() { + return lastLedgerBaseFee; + } + + public Long getLastLedger() { + return lastLedger; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/OrderBookResponse.java b/app/src/main/java/org/stellar/sdk/responses/OrderBookResponse.java new file mode 100644 index 0000000000..4aee846404 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/OrderBookResponse.java @@ -0,0 +1,77 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; +import org.stellar.sdk.Asset; +import org.stellar.sdk.Price; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents order book response. + * @see Order book documentation + * @see org.stellar.sdk.requests.OrderBookRequestBuilder + * @see org.stellar.sdk.Server#orderBook() + */ +public class OrderBookResponse extends Response { + @SerializedName("base") + private final Asset base; + @SerializedName("counter") + private final Asset counter; + @SerializedName("asks") + private final Row[] asks; + @SerializedName("bids") + private final Row[] bids; + + public OrderBookResponse(Asset base, Asset counter, Row[] asks, Row[] bids) { + this.base = base; + this.counter = counter; + this.asks = asks; + this.bids = bids; + } + + public Asset getBase() { + return base; + } + + public Asset getCounter() { + return counter; + } + + public Row[] getAsks() { + return asks; + } + + public Row[] getBids() { + return bids; + } + + /** + * Represents order book row. + */ + public static class Row { + @SerializedName("amount") + private final String amount; + @SerializedName("price") + private final String price; + @SerializedName("price_r") + private final Price priceR; + + Row(String amount, String price, Price priceR) { + this.amount = checkNotNull(amount, "amount cannot be null"); + this.price = checkNotNull(price, "price cannot be null"); + this.priceR = checkNotNull(priceR, "priceR cannot be null"); + } + + public String getAmount() { + return amount; + } + + public String getPrice() { + return price; + } + + public Price getPriceR() { + return priceR; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/Page.java b/app/src/main/java/org/stellar/sdk/responses/Page.java new file mode 100644 index 0000000000..109eb32d94 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/Page.java @@ -0,0 +1,93 @@ +package org.stellar.sdk.responses; + +import static java.util.Objects.requireNonNull; + +import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; + +import org.stellar.sdk.requests.ResponseHandler; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.ArrayList; + +import okhttp3.OkHttpClient; +import okhttp3.Request; + +/** + * Represents page of objects. + * @see Page documentation + */ +public class Page extends Response implements TypedResponse> { + + @SerializedName("records") + private ArrayList records; + @SerializedName("links") + private Links links; + + private TypeToken> type; + + Page() {} + + public ArrayList getRecords() { + return records; + } + + public Links getLinks() { + return links; + } + + /** + * @return The next page of results or null when there is no link for the next page of results + * @throws URISyntaxException + * @throws IOException + */ + public Page getNextPage(OkHttpClient httpClient) throws URISyntaxException, IOException { + if (this.getLinks().getNext() == null) { + return null; + } + TypeToken> type = requireNonNull(this.type, "type cannot be null, is it being correctly set after the creation of this " + getClass().getSimpleName() + "?"); + ResponseHandler> responseHandler = new ResponseHandler>(type); + String url = this.getLinks().getNext().getHref(); + + Request request = new Request.Builder().get().url(url).build(); + okhttp3.Response response = httpClient.newCall(request).execute(); + + return responseHandler.handleResponse(response); + } + + @Override + public void setType(TypeToken> type) { + this.type = type; + } + + /** + * Links connected to page response. + */ + public static class Links { + @SerializedName("next") + private final Link next; + @SerializedName("prev") + private final Link prev; + @SerializedName("self") + private final Link self; + + Links(Link next, Link prev, Link self) { + this.next = next; + this.prev = prev; + this.self = self; + } + + public Link getNext() { + return next; + } + + public Link getPrev() { + return prev; + } + + public Link getSelf() { + return self; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/PageDeserializer.java b/app/src/main/java/org/stellar/sdk/responses/PageDeserializer.java new file mode 100644 index 0000000000..d51fbd19df --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/PageDeserializer.java @@ -0,0 +1,51 @@ +package org.stellar.sdk.responses; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.reflect.TypeToken; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.effects.EffectResponse; +import org.stellar.sdk.responses.operations.OperationResponse; + +import java.lang.reflect.Type; + +class PageDeserializer implements JsonDeserializer> { + private TypeToken> pageType; + + /** + * "Generics on a type are typically erased at runtime, except when the type is compiled with the + * generic parameter bound. In that case, the compiler inserts the generic type information into + * the compiled class. In other cases, that is not possible." + * More info: http://stackoverflow.com/a/14506181 + * @param pageType + */ + public PageDeserializer(TypeToken> pageType) { + this.pageType = pageType; + } + + @Override + public Page deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + // Flatten the object so it has two fields `records` and `links` + JsonObject newJson = new JsonObject(); + newJson.add("records", json.getAsJsonObject().get("_embedded").getAsJsonObject().get("records")); + newJson.add("links", json.getAsJsonObject().get("_links")); + + // Create new Gson object with adapters needed in Page + Gson gson = new GsonBuilder() + .registerTypeAdapter(Asset.class, new AssetDeserializer()) + .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe()) + .registerTypeAdapter(OperationResponse.class, new OperationDeserializer()) + .registerTypeAdapter(EffectResponse.class, new EffectDeserializer()) + .registerTypeAdapter(TransactionResponse.class, new TransactionDeserializer()) + .create(); + + return gson.fromJson(newJson, pageType.getType()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/PathResponse.java b/app/src/main/java/org/stellar/sdk/responses/PathResponse.java new file mode 100644 index 0000000000..7b6acede3d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/PathResponse.java @@ -0,0 +1,104 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +import java.util.ArrayList; + +/** + * Represents path response. + * @see Path documentation + * @see org.stellar.sdk.requests.PathsRequestBuilder + * @see org.stellar.sdk.Server#paths() + */ +public class PathResponse extends Response { + @SerializedName("destination_amount") + private final String destinationAmount; + @SerializedName("destination_asset_type") + private final String destinationAssetType; + @SerializedName("destination_asset_code") + private final String destinationAssetCode; + @SerializedName("destination_asset_issuer") + private final String destinationAssetIssuer; + + @SerializedName("source_amount") + private final String sourceAmount; + @SerializedName("source_asset_type") + private final String sourceAssetType; + @SerializedName("source_asset_code") + private final String sourceAssetCode; + @SerializedName("source_asset_issuer") + private final String sourceAssetIssuer; + + @SerializedName("path") + private final ArrayList path; + + @SerializedName("_links") + private final Links links; + + PathResponse(String destinationAmount, String destinationAssetType, String destinationAssetCode, String destinationAssetIssuer, String sourceAmount, String sourceAssetType, String sourceAssetCode, String sourceAssetIssuer, ArrayList path, Links links) { + this.destinationAmount = destinationAmount; + this.destinationAssetType = destinationAssetType; + this.destinationAssetCode = destinationAssetCode; + this.destinationAssetIssuer = destinationAssetIssuer; + this.sourceAmount = sourceAmount; + this.sourceAssetType = sourceAssetType; + this.sourceAssetCode = sourceAssetCode; + this.sourceAssetIssuer = sourceAssetIssuer; + this.path = path; + this.links = links; + } + + public String getDestinationAmount() { + return destinationAmount; + } + + public String getSourceAmount() { + return sourceAmount; + } + + public ArrayList getPath() { + return path; + } + + public Asset getDestinationAsset() { + if (destinationAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(destinationAssetIssuer); + return Asset.createNonNativeAsset(destinationAssetCode, issuer); + } + } + + public Asset getSourceAsset() { + if (sourceAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(sourceAssetIssuer); + return Asset.createNonNativeAsset(sourceAssetCode, issuer); + } + } + + public Links getLinks() { + return links; + } + + /** + * Links connected to path. + */ + public static class Links { + @SerializedName("self") + private final Link self; + + Links(Link self) { + this.self = self; + } + + public Link getSelf() { + return self; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/Response.java b/app/src/main/java/org/stellar/sdk/responses/Response.java new file mode 100644 index 0000000000..6568ae3d87 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/Response.java @@ -0,0 +1,53 @@ +package org.stellar.sdk.responses; + +import okhttp3.Headers; + +public abstract class Response { + protected int rateLimitLimit; + protected int rateLimitRemaining; + protected int rateLimitReset; + + public void setHeaders(Headers headers) { + if (headers.get("X-Ratelimit-Limit") != null) { + this.rateLimitLimit = Integer.parseInt(headers.get("X-Ratelimit-Limit")); + } + if (headers.get("X-Ratelimit-Remaining") != null) { + this.rateLimitRemaining = Integer.parseInt(headers.get("X-Ratelimit-Remaining")); + } + if (headers.get("X-Ratelimit-Reset") != null) { + this.rateLimitReset = Integer.parseInt(headers.get("X-Ratelimit-Reset")); + } + } + + /** + * Returns X-RateLimit-Limit header from the response. + * This number represents the he maximum number of requests that the current client can + * make in one hour. + * @see Rate Limiting + */ + public int getRateLimitLimit() { + return rateLimitLimit; + } + + + public String getPagingToken() { + throw new UnsupportedOperationException("this response does not have a paging token"); + } + + /** + * Returns X-RateLimit-Remaining header from the response. + * The number of remaining requests for the current window. + * @see Rate Limiting + */ + public int getRateLimitRemaining() { + return rateLimitRemaining; + } + + /** + * Returns X-RateLimit-Reset header from the response. Seconds until a new window starts. + * @see Rate Limiting + */ + public int getRateLimitReset() { + return rateLimitReset; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/RootResponse.java b/app/src/main/java/org/stellar/sdk/responses/RootResponse.java new file mode 100644 index 0000000000..2b51432179 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/RootResponse.java @@ -0,0 +1,62 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents root endpoint response. + * @see org.stellar.sdk.Server#root() + */ +public class RootResponse extends Response { + @SerializedName("horizon_version") + private final String horizonVersion; + @SerializedName("core_version") + private final String stellarCoreVersion; + @SerializedName("history_latest_ledger") + private final int historyLatestLedger; + @SerializedName("history_elder_ledger") + private final int historyElderLedger; + @SerializedName("core_latest_ledger") + private final int coreLatestLedger; + @SerializedName("network_passphrase") + private final String networkPassphrase; + @SerializedName("protocol_version") + private final int protocolVersion; + + public String getHorizonVersion() { + return horizonVersion; + } + + public String getStellarCoreVersion() { + return stellarCoreVersion; + } + + public int getHistoryLatestLedger() { + return historyLatestLedger; + } + + public int getHistoryElderLedger() { + return historyElderLedger; + } + + public int getCoreLatestLedger() { + return coreLatestLedger; + } + + public String getNetworkPassphrase() { + return networkPassphrase; + } + + public int getProtocolVersion() { + return protocolVersion; + } + + public RootResponse(String horizonVersion, String stellarCoreVersion, int historyLatestLedger, int historyElderLedger, int coreLatestLedger, String networkPassphrase, int protocolVersion) { + this.horizonVersion = horizonVersion; + this.stellarCoreVersion = stellarCoreVersion; + this.historyLatestLedger = historyLatestLedger; + this.historyElderLedger = historyElderLedger; + this.coreLatestLedger = coreLatestLedger; + this.networkPassphrase = networkPassphrase; + this.protocolVersion = protocolVersion; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionResponse.java b/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionResponse.java new file mode 100644 index 0000000000..6bf5b4b851 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionResponse.java @@ -0,0 +1,182 @@ +package org.stellar.sdk.responses; + +import com.google.common.io.BaseEncoding; +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Server; +import org.stellar.sdk.xdr.OperationType; +import org.stellar.sdk.xdr.TransactionResult; +import org.stellar.sdk.xdr.XdrDataInputStream; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayList; + +/** + * Represents server response after submitting transaction. + * @see Server#submitTransaction(org.stellar.sdk.Transaction) + */ +public class SubmitTransactionResponse extends Response { + @SerializedName("hash") + private final String hash; + @SerializedName("ledger") + private final Long ledger; + @SerializedName("envelope_xdr") + private final String envelopeXdr; + @SerializedName("result_xdr") + private final String resultXdr; + @SerializedName("extras") + private final Extras extras; + + SubmitTransactionResponse(Extras extras, Long ledger, String hash, String envelopeXdr, String resultXdr) { + this.extras = extras; + this.ledger = ledger; + this.hash = hash; + this.envelopeXdr = envelopeXdr; + this.resultXdr = resultXdr; + } + + public boolean isSuccess() { + return ledger != null; + } + + public String getHash() { + return hash; + } + + public Long getLedger() { + return ledger; + } + + public String getEnvelopeXdr() { + if (this.isSuccess()) { + return this.envelopeXdr; + } else { + if (this.getExtras() != null) { + return this.getExtras().getEnvelopeXdr(); + } + return null; + } + } + + public String getResultXdr() { + if (this.isSuccess()) { + return this.resultXdr; + } else { + if (this.getExtras() != null) { + return this.getExtras().getResultXdr(); + } + return null; + } + } + + /** + * Helper method that returns Offer ID for ManageOffer from TransactionResult Xdr. + * This is helpful when you need ID of an offer to update it later. + * @param position Position of ManageOffer operation. If ManageOffer is second operation in this transaction this should be equal 1. + * @return Offer ID or null when operation at position is not a ManageOffer operation or error has occurred. + */ + public Long getOfferIdFromResult(int position) { + if (!this.isSuccess()) { + return null; + } + + BaseEncoding base64Encoding = BaseEncoding.base64(); + byte[] bytes = base64Encoding.decode(this.getResultXdr()); + ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); + XdrDataInputStream xdrInputStream = new XdrDataInputStream(inputStream); + TransactionResult result; + + try { + result = TransactionResult.decode(xdrInputStream); + } catch (IOException e) { + return null; + } + + if (result.getResult().getResults()[position] == null) { + return null; + } + + if (result.getResult().getResults()[position].getTr().getDiscriminant() != OperationType.MANAGE_OFFER) { + return null; + } + + if (result.getResult().getResults()[0].getTr().getManageOfferResult().getSuccess().getOffer().getOffer() == null) { + return null; + } + + return result.getResult().getResults()[0].getTr().getManageOfferResult().getSuccess().getOffer().getOffer().getOfferID().getUint64(); + } + + /** + * Additional information returned by a server. This will be null if transaction succeeded. + */ + public Extras getExtras() { + return extras; + } + + /** + * Additional information returned by a server. + */ + public static class Extras { + @SerializedName("envelope_xdr") + private final String envelopeXdr; + @SerializedName("result_xdr") + private final String resultXdr; + @SerializedName("result_codes") + private final ResultCodes resultCodes; + + Extras(String envelopeXdr, String resultXdr, ResultCodes resultCodes) { + this.envelopeXdr = envelopeXdr; + this.resultXdr = resultXdr; + this.resultCodes = resultCodes; + } + + /** + * Returns XDR TransactionEnvelope base64-encoded string. + * Use xdr-viewer to debug. + */ + public String getEnvelopeXdr() { + return envelopeXdr; + } + + /** + * Returns XDR TransactionResult base64-encoded string + * Use xdr-viewer to debug. + */ + public String getResultXdr() { + return resultXdr; + } + + /** + * Returns ResultCodes object that contains result codes for transaction. + */ + public ResultCodes getResultCodes() { + return resultCodes; + } + + /** + * Contains result codes for this transaction. + * @see Possible values + */ + public static class ResultCodes { + @SerializedName("transaction") + private final String transactionResultCode; + @SerializedName("operations") + private final ArrayList operationsResultCodes; + + public ResultCodes(String transactionResultCode, ArrayList operationsResultCodes) { + this.transactionResultCode = transactionResultCode; + this.operationsResultCodes = operationsResultCodes; + } + + public String getTransactionResultCode() { + return transactionResultCode; + } + + public ArrayList getOperationsResultCodes() { + return operationsResultCodes; + } + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionTimeoutResponseException.java b/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionTimeoutResponseException.java new file mode 100644 index 0000000000..1ca5471985 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionTimeoutResponseException.java @@ -0,0 +1,8 @@ +package org.stellar.sdk.responses; + +public class SubmitTransactionTimeoutResponseException extends RuntimeException { + @Override + public String getMessage() { + return "Timeout. Please resubmit your transaction to receive submission status. More info: https://www.stellar.org/developers/horizon/reference/errors/timeout.html"; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionUnknownResponseException.java b/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionUnknownResponseException.java new file mode 100644 index 0000000000..227d02bb03 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/SubmitTransactionUnknownResponseException.java @@ -0,0 +1,24 @@ +package org.stellar.sdk.responses; + +public class SubmitTransactionUnknownResponseException extends RuntimeException { + private int code; + private String body; + + public SubmitTransactionUnknownResponseException(int code, String body) { + this.code = code; + this.body = body; + } + + @Override + public String getMessage() { + return "Unknown response from Horizon"; + } + + public int getCode() { + return code; + } + + public String getBody() { + return body; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/TradeAggregationResponse.java b/app/src/main/java/org/stellar/sdk/responses/TradeAggregationResponse.java new file mode 100644 index 0000000000..08fc492d37 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/TradeAggregationResponse.java @@ -0,0 +1,78 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; + +import java.util.Date; + +public class TradeAggregationResponse extends Response { + @SerializedName("timestamp") + private final long timestamp; + @SerializedName("trade_count") + private final int tradeCount; + @SerializedName("base_volume") + private final String baseVolume; + @SerializedName("counter_volume") + private final String counterVolume; + @SerializedName("avg") + private final String avg; + @SerializedName("high") + private final String high; + @SerializedName("low") + private final String low; + @SerializedName("open") + private final String open; + @SerializedName("close") + private final String close; + + public TradeAggregationResponse(long timestamp, int tradeCount, String baseVolume, String counterVolume, String avg, String high, String low, String open, String close) { + this.timestamp = timestamp; + this.tradeCount = tradeCount; + this.baseVolume = baseVolume; + this.counterVolume = counterVolume; + this.avg = avg; + this.high = high; + this.low = low; + this.open = open; + this.close = close; + } + + public long getTimestamp() { + return timestamp; + } + + public Date getDate() { + return new Date(Long.valueOf(this.timestamp)); + } + + public int getTradeCount() { + return tradeCount; + } + + public String getBaseVolume() { + return baseVolume; + } + + public String getCounterVolume() { + return counterVolume; + } + + public String getAvg() { + return avg; + } + + public String getHigh() { + return high; + } + + public String getLow() { + return low; + } + + public String getOpen() { + return open; + } + + public String getClose() { + return close; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/TradeResponse.java b/app/src/main/java/org/stellar/sdk/responses/TradeResponse.java new file mode 100644 index 0000000000..f45c7bbe8c --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/TradeResponse.java @@ -0,0 +1,195 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; +import org.stellar.sdk.Asset; +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.Price; +; + +/** + * Represents trades response. + * @see Trades documentation + * @see org.stellar.sdk.requests.TradesRequestBuilder + * @see org.stellar.sdk.Server#trades() + */ +public class TradeResponse extends Response { + @SerializedName("id") + private final String id; + @SerializedName("paging_token") + private final String pagingToken; + @SerializedName("ledger_close_time") + private final String ledgerCloseTime; + + @SerializedName("offer_id") + private final String offerId; + + @SerializedName("base_is_seller") + protected final boolean baseIsSeller; + + @SerializedName("base_account") + protected final KeyPair baseAccount; + @SerializedName("base_offer_id") + private final String baseOfferId; + @SerializedName("base_amount") + protected final String baseAmount; + @SerializedName("base_asset_type") + protected final String baseAssetType; + @SerializedName("base_asset_code") + protected final String baseAssetCode; + @SerializedName("base_asset_issuer") + protected final String baseAssetIssuer; + + @SerializedName("counter_account") + protected final KeyPair counterAccount; + @SerializedName("counter_offer_id") + private final String counterOfferId; + @SerializedName("counter_amount") + protected final String counterAmount; + @SerializedName("counter_asset_type") + protected final String counterAssetType; + @SerializedName("counter_asset_code") + protected final String counterAssetCode; + @SerializedName("counter_asset_issuer") + protected final String counterAssetIssuer; + + @SerializedName("price") + protected final Price price; + + @SerializedName("_links") + private TradeResponse.Links links; + + public TradeResponse(String id, String pagingToken, String ledgerCloseTime, String offerId, boolean baseIsSeller, KeyPair baseAccount, String baseOfferId, String baseAmount, String baseAssetType, String baseAssetCode, String baseAssetIssuer, KeyPair counterAccount, String counterOfferId, String counterAmount, String counterAssetType, String counterAssetCode, String counterAssetIssuer, Price price) { + this.id = id; + this.pagingToken = pagingToken; + this.ledgerCloseTime = ledgerCloseTime; + this.offerId = offerId; + this.baseIsSeller = baseIsSeller; + this.baseAccount = baseAccount; + this.baseOfferId = baseOfferId; + this.baseAmount = baseAmount; + this.baseAssetType = baseAssetType; + this.baseAssetCode = baseAssetCode; + this.baseAssetIssuer = baseAssetIssuer; + this.counterAccount = counterAccount; + this.counterOfferId = counterOfferId; + this.counterAmount = counterAmount; + this.counterAssetType = counterAssetType; + this.counterAssetCode = counterAssetCode; + this.counterAssetIssuer = counterAssetIssuer; + this.price = price; + } + + public String getId() { + return id; + } + + public String getPagingToken() { + return pagingToken; + } + + public String getLedgerCloseTime() { + return ledgerCloseTime; + } + + public String getOfferId() { + return offerId; + } + + public boolean isBaseSeller() { + return baseIsSeller; + } + + public String getBaseOfferId() { + return baseOfferId; + } + + public KeyPair getBaseAccount() { + return baseAccount; + } + + public String getBaseAmount() { + return baseAmount; + } + + public Asset getBaseAsset() { + return Asset.create(this.baseAssetType, this.baseAssetCode, this.baseAssetIssuer); + } + + public String getBaseAssetType() { + return baseAssetType; + } + + public String getBaseAssetCode() { + return baseAssetCode; + } + + public String getBaseAssetIssuer() { + return baseAssetIssuer; + } + + public KeyPair getCounterAccount() { + return counterAccount; + } + + public String getCounterOfferId() { + return counterOfferId; + } + + public Asset getCounterAsset() { + return Asset.create(this.counterAssetType, this.counterAssetCode, this.counterAssetIssuer); + } + + public String getCounterAmount() { + return counterAmount; + } + + public String getCounterAssetType() { + return counterAssetType; + } + + public String getCounterAssetCode() { + return counterAssetCode; + } + + public String getCounterAssetIssuer() { + return counterAssetIssuer; + } + + public Price getPrice() { + return price; + } + + public Links getLinks() { + return links; + } + + /** + * Links connected to a trade. + */ + public static class Links { + @SerializedName("base") + private final Link base; + @SerializedName("counter") + private final Link counter; + @SerializedName("operation") + private final Link operation; + + public Links(Link base, Link counter, Link operation) { + this.base = base; + this.counter = counter; + this.operation = operation; + } + + public Link getBase() { + return base; + } + + public Link getCounter() { + return counter; + } + + public Link getOperation() { + return operation; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/TransactionDeserializer.java b/app/src/main/java/org/stellar/sdk/responses/TransactionDeserializer.java new file mode 100644 index 0000000000..9e1e6b325c --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/TransactionDeserializer.java @@ -0,0 +1,60 @@ +package org.stellar.sdk.responses; + +import com.google.common.io.BaseEncoding; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.Memo; + +import java.lang.reflect.Type; + +public class TransactionDeserializer implements JsonDeserializer { + @Override + public TransactionResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + // Create new Gson object with adapters needed in Transaction + Gson gson = new GsonBuilder() + .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe()) + .create(); + + TransactionResponse transaction = gson.fromJson(json, TransactionResponse.class); + + String memoType = json.getAsJsonObject().get("memo_type").getAsString(); + Memo memo; + if (memoType.equals("none")) { + memo = Memo.none(); + } else { + // Because of the way "encoding/json" works on structs in Go, if transaction + // has an empty `memo_text` value, the `memo` field won't be present in a JSON + // representation of a transaction. That's why we need to handle a special case + // here. + if (memoType.equals("text")) { + JsonElement memoField = json.getAsJsonObject().get("memo"); + if (memoField != null) { + memo = Memo.text(memoField.getAsString()); + } else { + memo = Memo.text(""); + } + } else { + String memoValue = json.getAsJsonObject().get("memo").getAsString(); + BaseEncoding base64Encoding = BaseEncoding.base64(); + if (memoType.equals("id")) { + memo = Memo.id(Long.parseUnsignedLong(memoValue)); + } else if (memoType.equals("hash")) { + memo = Memo.hash(base64Encoding.decode(memoValue)); + } else if (memoType.equals("return")) { + memo = Memo.returnHash(base64Encoding.decode(memoValue)); + } else { + throw new JsonParseException("Unknown memo type."); + } + } + } + + transaction.setMemo(memo); + return transaction; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/TransactionResponse.java b/app/src/main/java/org/stellar/sdk/responses/TransactionResponse.java new file mode 100644 index 0000000000..f7e2cbe1f4 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/TransactionResponse.java @@ -0,0 +1,179 @@ +package org.stellar.sdk.responses; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.Memo; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Represents transaction response. + * @see Transaction documentation + * @see org.stellar.sdk.requests.TransactionsRequestBuilder + * @see org.stellar.sdk.Server#transactions() + */ +public class TransactionResponse extends Response { + @SerializedName("hash") + private final String hash; + @SerializedName("ledger") + private final Long ledger; + @SerializedName("created_at") + private final String createdAt; + @SerializedName("source_account") + private final KeyPair sourceAccount; + @SerializedName("paging_token") + private final String pagingToken; + @SerializedName("source_account_sequence") + private final Long sourceAccountSequence; + @SerializedName("fee_paid") + private final Long feePaid; + @SerializedName("operation_count") + private final Integer operationCount; + @SerializedName("envelope_xdr") + private final String envelopeXdr; + @SerializedName("result_xdr") + private final String resultXdr; + @SerializedName("result_meta_xdr") + private final String resultMetaXdr; + @SerializedName("_links") + private final Links links; + + // GSON won't serialize `transient` variables automatically. We need this behaviour + // because Memo is an abstract class and GSON tries to instantiate it. + private transient Memo memo; + + TransactionResponse(String hash, Long ledger, String createdAt, KeyPair sourceAccount, String pagingToken, Long sourceAccountSequence, Long feePaid, Integer operationCount, String envelopeXdr, String resultXdr, String resultMetaXdr, Memo memo, Links links) { + this.hash = hash; + this.ledger = ledger; + this.createdAt = createdAt; + this.sourceAccount = sourceAccount; + this.pagingToken = pagingToken; + this.sourceAccountSequence = sourceAccountSequence; + this.feePaid = feePaid; + this.operationCount = operationCount; + this.envelopeXdr = envelopeXdr; + this.resultXdr = resultXdr; + this.resultMetaXdr = resultMetaXdr; + this.memo = memo; + this.links = links; + } + + public String getHash() { + return hash; + } + + public Long getLedger() { + return ledger; + } + + public String getCreatedAt() { + return createdAt; + } + + public KeyPair getSourceAccount() { + return sourceAccount; + } + + public String getPagingToken() { + return pagingToken; + } + + public Long getSourceAccountSequence() { + return sourceAccountSequence; + } + + public Long getFeePaid() { + return feePaid; + } + + public Integer getOperationCount() { + return operationCount; + } + + public String getEnvelopeXdr() { + return envelopeXdr; + } + + public String getResultXdr() { + return resultXdr; + } + + public String getResultMetaXdr() { + return resultMetaXdr; + } + + public Memo getMemo() { + return memo; + } + + public void setMemo(Memo memo) { + memo = checkNotNull(memo, "memo cannot be null"); + if (this.memo != null) { + throw new RuntimeException("Memo has been already set."); + } + this.memo = memo; + } + + public Links getLinks() { + return links; + } + + /** + * Links connected to transaction. + */ + public static class Links { + @SerializedName("account") + private final Link account; + @SerializedName("effects") + private final Link effects; + @SerializedName("ledger") + private final Link ledger; + @SerializedName("operations") + private final Link operations; + @SerializedName("precedes") + private final Link precedes; + @SerializedName("self") + private final Link self; + @SerializedName("succeeds") + private final Link succeeds; + + Links(Link account, Link effects, Link ledger, Link operations, Link self, Link precedes, Link succeeds) { + this.account = account; + this.effects = effects; + this.ledger = ledger; + this.operations = operations; + this.self = self; + this.precedes = precedes; + this.succeeds = succeeds; + } + + public Link getAccount() { + return account; + } + + public Link getEffects() { + return effects; + } + + public Link getLedger() { + return ledger; + } + + public Link getOperations() { + return operations; + } + + public Link getPrecedes() { + return precedes; + } + + public Link getSelf() { + return self; + } + + public Link getSucceeds() { + return succeeds; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/TypedResponse.java b/app/src/main/java/org/stellar/sdk/responses/TypedResponse.java new file mode 100644 index 0000000000..f645072349 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/TypedResponse.java @@ -0,0 +1,14 @@ +package org.stellar.sdk.responses; + +import com.google.gson.reflect.TypeToken; + +/** + * Indicates a generic container that requires type information to be provided after initialisation. + * + * @param the type of the objects in this response container. + */ +public interface TypedResponse { + + void setType(TypeToken type); + +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/AccountCreatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/AccountCreatedEffectResponse.java new file mode 100644 index 0000000000..7e5f089604 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/AccountCreatedEffectResponse.java @@ -0,0 +1,22 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents account_created effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class AccountCreatedEffectResponse extends EffectResponse { + @SerializedName("starting_balance") + protected final String startingBalance; + + AccountCreatedEffectResponse(String startingBalance) { + this.startingBalance = startingBalance; + } + + public String getStartingBalance() { + return startingBalance; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/AccountCreditedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/AccountCreditedEffectResponse.java new file mode 100644 index 0000000000..952da6512d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/AccountCreditedEffectResponse.java @@ -0,0 +1,45 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + + +/** + * Represents account_credited effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class AccountCreditedEffectResponse extends EffectResponse { + @SerializedName("amount") + protected final String amount; + @SerializedName("asset_type") + protected final String assetType; + @SerializedName("asset_code") + protected final String assetCode; + @SerializedName("asset_issuer") + protected final String assetIssuer; + + AccountCreditedEffectResponse(String amount, String assetType, String assetCode, String assetIssuer) { + this.amount = amount; + this.assetType = assetType; + this.assetCode = assetCode; + this.assetIssuer = assetIssuer; + } + + public String getAmount() { + return amount; + } + + public Asset getAsset() { + if (assetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(assetIssuer); + return Asset.createNonNativeAsset(assetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/AccountDebitedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/AccountDebitedEffectResponse.java new file mode 100644 index 0000000000..d51f9b3e12 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/AccountDebitedEffectResponse.java @@ -0,0 +1,44 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +/** + * Represents account_debited effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class AccountDebitedEffectResponse extends EffectResponse { + @SerializedName("amount") + protected final String amount; + @SerializedName("asset_type") + protected final String assetType; + @SerializedName("asset_code") + protected final String assetCode; + @SerializedName("asset_issuer") + protected final String assetIssuer; + + AccountDebitedEffectResponse(String amount, String assetType, String assetCode, String assetIssuer) { + this.amount = amount; + this.assetType = assetType; + this.assetCode = assetCode; + this.assetIssuer = assetIssuer; + } + + public String getAmount() { + return amount; + } + + public Asset getAsset() { + if (assetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(assetIssuer); + return Asset.createNonNativeAsset(assetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/AccountFlagsUpdatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/AccountFlagsUpdatedEffectResponse.java new file mode 100644 index 0000000000..5585d71c42 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/AccountFlagsUpdatedEffectResponse.java @@ -0,0 +1,29 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents account_flags_updated effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class AccountFlagsUpdatedEffectResponse extends EffectResponse { + @SerializedName("auth_required_flag") + protected final Boolean authRequiredFlag; + @SerializedName("auth_revokable_flag") + protected final Boolean authRevokableFlag; + + AccountFlagsUpdatedEffectResponse(Boolean authRequiredFlag, Boolean authRevokableFlag) { + this.authRequiredFlag = authRequiredFlag; + this.authRevokableFlag = authRevokableFlag; + } + + public Boolean getAuthRequiredFlag() { + return authRequiredFlag; + } + + public Boolean getAuthRevokableFlag() { + return authRevokableFlag; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/AccountHomeDomainUpdatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/AccountHomeDomainUpdatedEffectResponse.java new file mode 100644 index 0000000000..7e4e687e0d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/AccountHomeDomainUpdatedEffectResponse.java @@ -0,0 +1,22 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents account_home_domain_updated effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class AccountHomeDomainUpdatedEffectResponse extends EffectResponse { + @SerializedName("home_domain") + protected final String homeDomain; + + AccountHomeDomainUpdatedEffectResponse(String homeDomain) { + this.homeDomain = homeDomain; + } + + public String getHomeDomain() { + return homeDomain; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/AccountInflationDestinationUpdatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/AccountInflationDestinationUpdatedEffectResponse.java new file mode 100644 index 0000000000..b6fcfac9fe --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/AccountInflationDestinationUpdatedEffectResponse.java @@ -0,0 +1,11 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents account_inflation_destination_updated effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class AccountInflationDestinationUpdatedEffectResponse extends EffectResponse { + // +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/AccountRemovedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/AccountRemovedEffectResponse.java new file mode 100644 index 0000000000..44ce787653 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/AccountRemovedEffectResponse.java @@ -0,0 +1,9 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents account_removed effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class AccountRemovedEffectResponse extends EffectResponse {} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/AccountThresholdsUpdatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/AccountThresholdsUpdatedEffectResponse.java new file mode 100644 index 0000000000..b675efb9e0 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/AccountThresholdsUpdatedEffectResponse.java @@ -0,0 +1,36 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents account_thresholds_updated effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class AccountThresholdsUpdatedEffectResponse extends EffectResponse { + @SerializedName("low_threshold") + protected final Integer lowThreshold; + @SerializedName("med_threshold") + protected final Integer medThreshold; + @SerializedName("high_threshold") + protected final Integer highThreshold; + + AccountThresholdsUpdatedEffectResponse(Integer lowThreshold, Integer medThreshold, Integer highThreshold) { + this.lowThreshold = lowThreshold; + this.medThreshold = medThreshold; + this.highThreshold = highThreshold; + } + + public Integer getLowThreshold() { + return lowThreshold; + } + + public Integer getMedThreshold() { + return medThreshold; + } + + public Integer getHighThreshold() { + return highThreshold; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/DataCreatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/DataCreatedEffectResponse.java new file mode 100644 index 0000000000..fbfc093671 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/DataCreatedEffectResponse.java @@ -0,0 +1,11 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents data_created effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class DataCreatedEffectResponse extends EffectResponse { + // +} \ No newline at end of file diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/DataRemovedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/DataRemovedEffectResponse.java new file mode 100644 index 0000000000..ca3f758dda --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/DataRemovedEffectResponse.java @@ -0,0 +1,11 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents data_removed effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class DataRemovedEffectResponse extends EffectResponse { + // +} \ No newline at end of file diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/DataUpdatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/DataUpdatedEffectResponse.java new file mode 100644 index 0000000000..31ff963eb3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/DataUpdatedEffectResponse.java @@ -0,0 +1,11 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents data_updated effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class DataUpdatedEffectResponse extends EffectResponse { + // +} \ No newline at end of file diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/EffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/EffectResponse.java new file mode 100644 index 0000000000..83a6d2e9bb --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/EffectResponse.java @@ -0,0 +1,111 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.Link; +import org.stellar.sdk.responses.Response; + +/** + * Abstract class for effect responses. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public abstract class EffectResponse extends Response { + @SerializedName("id") + protected String id; + @SerializedName("account") + protected KeyPair account; + @SerializedName("type") + protected String type; + @SerializedName("created_at") + protected String createdAt; + @SerializedName("paging_token") + protected String pagingToken; + @SerializedName("_links") + private Links links; + + public String getId() { + return id; + } + + public KeyPair getAccount() { + return account; + } + + /** + *

Returns effect type. Possible types:

+ *
    + *
  • account_created
  • + *
  • account_removed
  • + *
  • account_credited
  • + *
  • account_debited
  • + *
  • account_thresholds_updated
  • + *
  • account_home_domain_updated
  • + *
  • account_flags_updated
  • + *
  • account_inflation_destination_updated
  • + *
  • signer_created
  • + *
  • signer_removed
  • + *
  • signer_updated
  • + *
  • trustline_created
  • + *
  • trustline_removed
  • + *
  • trustline_updated
  • + *
  • trustline_authorized
  • + *
  • trustline_deauthorized
  • + *
  • offer_created
  • + *
  • offer_removed
  • + *
  • offer_updated
  • + *
  • trade
  • + *
  • data_created
  • + *
  • data_removed
  • + *
  • data_updated
  • + *
  • sequence_bumped
  • + *
+ */ + public String getType() { + return type; + } + + public String getPagingToken() { + return pagingToken; + } + + public String getCreatedAt() { + return createdAt; + } + + public Links getLinks() { + return links; + } + + /** + * Represents effect links. + */ + public static class Links { + @SerializedName("operation") + private final Link operation; + @SerializedName("precedes") + private final Link precedes; + @SerializedName("succeeds") + private final Link succeeds; + + public Links(Link operation, Link precedes, Link succeeds) { + this.operation = operation; + this.precedes = precedes; + this.succeeds = succeeds; + } + + public Link getOperation() { + return operation; + } + + public Link getPrecedes() { + return precedes; + } + + public Link getSucceeds() { + return succeeds; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/OfferCreatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/OfferCreatedEffectResponse.java new file mode 100644 index 0000000000..aaf2c96ed0 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/OfferCreatedEffectResponse.java @@ -0,0 +1,11 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents offer_created effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class OfferCreatedEffectResponse extends EffectResponse { + // +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/OfferRemovedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/OfferRemovedEffectResponse.java new file mode 100644 index 0000000000..2bf136758b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/OfferRemovedEffectResponse.java @@ -0,0 +1,11 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents offer_removed effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class OfferRemovedEffectResponse extends EffectResponse { + // +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/OfferUpdatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/OfferUpdatedEffectResponse.java new file mode 100644 index 0000000000..fe9e6128c3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/OfferUpdatedEffectResponse.java @@ -0,0 +1,11 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents offer_updated effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class OfferUpdatedEffectResponse extends EffectResponse { + // +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/SequenceBumpedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/SequenceBumpedEffectResponse.java new file mode 100644 index 0000000000..f7243bb71f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/SequenceBumpedEffectResponse.java @@ -0,0 +1,22 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents sequence_bumped effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class SequenceBumpedEffectResponse extends EffectResponse { + @SerializedName("new_seq") + protected final Long newSequence; + + public SequenceBumpedEffectResponse(Long newSequence) { + this.newSequence = newSequence; + } + + public Long getNewSequence() { + return newSequence; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/SignerCreatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/SignerCreatedEffectResponse.java new file mode 100644 index 0000000000..9b9bb02f41 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/SignerCreatedEffectResponse.java @@ -0,0 +1,13 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents signer_created effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class SignerCreatedEffectResponse extends SignerEffectResponse { + SignerCreatedEffectResponse(Integer weight, String publicKey) { + super(weight, publicKey); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/SignerEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/SignerEffectResponse.java new file mode 100644 index 0000000000..d02dc4725e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/SignerEffectResponse.java @@ -0,0 +1,23 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +abstract class SignerEffectResponse extends EffectResponse { + @SerializedName("weight") + protected final Integer weight; + @SerializedName("public_key") + protected final String publicKey; + + public SignerEffectResponse(Integer weight, String publicKey) { + this.weight = weight; + this.publicKey = publicKey; + } + + public Integer getWeight() { + return weight; + } + + public String getPublicKey() { + return publicKey; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/SignerRemovedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/SignerRemovedEffectResponse.java new file mode 100644 index 0000000000..69ec1886a8 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/SignerRemovedEffectResponse.java @@ -0,0 +1,10 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents signer_removed effect response. + */ +public class SignerRemovedEffectResponse extends SignerEffectResponse { + SignerRemovedEffectResponse(Integer weight, String publicKey) { + super(weight, publicKey); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/SignerUpdatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/SignerUpdatedEffectResponse.java new file mode 100644 index 0000000000..12865740cf --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/SignerUpdatedEffectResponse.java @@ -0,0 +1,13 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents signed_updated effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class SignerUpdatedEffectResponse extends SignerEffectResponse { + SignerUpdatedEffectResponse(Integer weight, String publicKey) { + super(weight, publicKey); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/TradeEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/TradeEffectResponse.java new file mode 100644 index 0000000000..cf7acf007e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/TradeEffectResponse.java @@ -0,0 +1,85 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +/** + * Represents trade effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class TradeEffectResponse extends EffectResponse { + @SerializedName("seller") + protected final KeyPair seller; + @SerializedName("offer_id") + protected final Long offerId; + + @SerializedName("sold_amount") + protected final String soldAmount; + @SerializedName("sold_asset_type") + protected final String soldAssetType; + @SerializedName("sold_asset_code") + protected final String soldAssetCode; + @SerializedName("sold_asset_issuer") + protected final String soldAssetIssuer; + + @SerializedName("bought_amount") + protected final String boughtAmount; + @SerializedName("bought_asset_type") + protected final String boughtAssetType; + @SerializedName("bought_asset_code") + protected final String boughtAssetCode; + @SerializedName("bought_asset_issuer") + protected final String boughtAssetIssuer; + + TradeEffectResponse(KeyPair seller, Long offerId, String soldAmount, String soldAssetType, String soldAssetCode, String soldAssetIssuer, String boughtAmount, String boughtAssetType, String boughtAssetCode, String boughtAssetIssuer) { + this.seller = seller; + this.offerId = offerId; + this.soldAmount = soldAmount; + this.soldAssetType = soldAssetType; + this.soldAssetCode = soldAssetCode; + this.soldAssetIssuer = soldAssetIssuer; + this.boughtAmount = boughtAmount; + this.boughtAssetType = boughtAssetType; + this.boughtAssetCode = boughtAssetCode; + this.boughtAssetIssuer = boughtAssetIssuer; + } + + public KeyPair getSeller() { + return seller; + } + + public Long getOfferId() { + return offerId; + } + + public String getSoldAmount() { + return soldAmount; + } + + public String getBoughtAmount() { + return boughtAmount; + } + + public Asset getSoldAsset() { + if (soldAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(soldAssetIssuer); + return Asset.createNonNativeAsset(soldAssetCode, issuer); + } + } + + public Asset getBoughtAsset() { + if (boughtAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(boughtAssetIssuer); + return Asset.createNonNativeAsset(boughtAssetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineAuthorizationResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineAuthorizationResponse.java new file mode 100644 index 0000000000..92d3e1d0a8 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineAuthorizationResponse.java @@ -0,0 +1,32 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.KeyPair; + +abstract class TrustlineAuthorizationResponse extends EffectResponse { + @SerializedName("trustor") + protected final KeyPair trustor; + @SerializedName("asset_type") + protected final String assetType; + @SerializedName("asset_code") + protected final String assetCode; + + TrustlineAuthorizationResponse(KeyPair trustor, String assetType, String assetCode) { + this.trustor = trustor; + this.assetType = assetType; + this.assetCode = assetCode; + } + + public KeyPair getTrustor() { + return trustor; + } + + public String getAssetType() { + return assetType; + } + + public String getAssetCode() { + return assetCode; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineAuthorizedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineAuthorizedEffectResponse.java new file mode 100644 index 0000000000..6d258d848a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineAuthorizedEffectResponse.java @@ -0,0 +1,15 @@ +package org.stellar.sdk.responses.effects; + +import org.stellar.sdk.KeyPair; + +/** + * Represents trustline_authorized effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class TrustlineAuthorizedEffectResponse extends TrustlineAuthorizationResponse { + TrustlineAuthorizedEffectResponse(KeyPair trustor, String assetType, String assetCode) { + super(trustor, assetType, assetCode); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineCUDResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineCUDResponse.java new file mode 100644 index 0000000000..65d2ff618b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineCUDResponse.java @@ -0,0 +1,38 @@ +package org.stellar.sdk.responses.effects; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +abstract class TrustlineCUDResponse extends EffectResponse { + @SerializedName("limit") + protected final String limit; + @SerializedName("asset_type") + protected final String assetType; + @SerializedName("asset_code") + protected final String assetCode; + @SerializedName("asset_issuer") + protected final String assetIssuer; + + public TrustlineCUDResponse(String limit, String assetType, String assetCode, String assetIssuer) { + this.limit = limit; + this.assetType = assetType; + this.assetCode = assetCode; + this.assetIssuer = assetIssuer; + } + + public String getLimit() { + return limit; + } + + public Asset getAsset() { + if (assetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(assetIssuer); + return Asset.createNonNativeAsset(assetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineCreatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineCreatedEffectResponse.java new file mode 100644 index 0000000000..e600b54643 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineCreatedEffectResponse.java @@ -0,0 +1,13 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents trustline_created effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class TrustlineCreatedEffectResponse extends TrustlineCUDResponse { + TrustlineCreatedEffectResponse(String limit, String assetType, String assetCode, String assetIssuer) { + super(limit, assetType, assetCode, assetIssuer); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineDeauthorizedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineDeauthorizedEffectResponse.java new file mode 100644 index 0000000000..84cf1712c7 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineDeauthorizedEffectResponse.java @@ -0,0 +1,15 @@ +package org.stellar.sdk.responses.effects; + +import org.stellar.sdk.KeyPair; + +/** + * Represents trustline_deauthorized effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class TrustlineDeauthorizedEffectResponse extends TrustlineAuthorizationResponse { + TrustlineDeauthorizedEffectResponse(KeyPair trustor, String assetType, String assetCode) { + super(trustor, assetType, assetCode); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineRemovedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineRemovedEffectResponse.java new file mode 100644 index 0000000000..0936d620df --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineRemovedEffectResponse.java @@ -0,0 +1,13 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents trustline_removed effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class TrustlineRemovedEffectResponse extends TrustlineCUDResponse { + TrustlineRemovedEffectResponse(String limit, String assetType, String assetCode, String assetIssuer) { + super(limit, assetType, assetCode, assetIssuer); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineUpdatedEffectResponse.java b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineUpdatedEffectResponse.java new file mode 100644 index 0000000000..a1c085f0d9 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/effects/TrustlineUpdatedEffectResponse.java @@ -0,0 +1,13 @@ +package org.stellar.sdk.responses.effects; + +/** + * Represents trustline_updated effect response. + * @see Effect documentation + * @see org.stellar.sdk.requests.EffectsRequestBuilder + * @see org.stellar.sdk.Server#effects() + */ +public class TrustlineUpdatedEffectResponse extends TrustlineCUDResponse { + TrustlineUpdatedEffectResponse(String limit, String assetType, String assetCode, String assetIssuer) { + super(limit, assetType, assetCode, assetIssuer); + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/AccountMergeOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/AccountMergeOperationResponse.java new file mode 100644 index 0000000000..6856a7a981 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/AccountMergeOperationResponse.java @@ -0,0 +1,31 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.KeyPair; + +/** + * Represents AccountMerge operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class AccountMergeOperationResponse extends OperationResponse { + @SerializedName("account") + protected final KeyPair account; + @SerializedName("into") + protected final KeyPair into; + + AccountMergeOperationResponse(KeyPair account, KeyPair into) { + this.account = account; + this.into = into; + } + + public KeyPair getAccount() { + return account; + } + + public KeyPair getInto() { + return into; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/AllowTrustOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/AllowTrustOperationResponse.java new file mode 100644 index 0000000000..b394a6b3b6 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/AllowTrustOperationResponse.java @@ -0,0 +1,58 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +/** + * Represents AllowTrust operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class AllowTrustOperationResponse extends OperationResponse { + @SerializedName("trustor") + protected final KeyPair trustor; + @SerializedName("trustee") + protected final KeyPair trustee; + @SerializedName("asset_type") + protected final String assetType; + @SerializedName("asset_code") + protected final String assetCode; + @SerializedName("asset_issuer") + protected final String assetIssuer; + @SerializedName("authorize") + protected final boolean authorize; + + AllowTrustOperationResponse(boolean authorize, String assetIssuer, String assetCode, String assetType, KeyPair trustee, KeyPair trustor) { + this.authorize = authorize; + this.assetIssuer = assetIssuer; + this.assetCode = assetCode; + this.assetType = assetType; + this.trustee = trustee; + this.trustor = trustor; + } + + public KeyPair getTrustor() { + return trustor; + } + + public KeyPair getTrustee() { + return trustee; + } + + public boolean isAuthorize() { + return authorize; + } + + public Asset getAsset() { + if (assetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(assetIssuer); + return Asset.createNonNativeAsset(assetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/BumpSequenceOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/BumpSequenceOperationResponse.java new file mode 100644 index 0000000000..edfe9259ba --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/BumpSequenceOperationResponse.java @@ -0,0 +1,22 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents BumpSequence operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class BumpSequenceOperationResponse extends OperationResponse { + @SerializedName("bump_to") + protected final Long bumpTo; + + public BumpSequenceOperationResponse(Long bumpTo) { + this.bumpTo = bumpTo; + } + + public Long getBumpTo() { + return bumpTo; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/ChangeTrustOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/ChangeTrustOperationResponse.java new file mode 100644 index 0000000000..33e167eb3f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/ChangeTrustOperationResponse.java @@ -0,0 +1,58 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +/** + * Represents ChangeTrust operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class ChangeTrustOperationResponse extends OperationResponse { + @SerializedName("trustor") + protected final KeyPair trustor; + @SerializedName("trustee") + protected final KeyPair trustee; + @SerializedName("asset_type") + protected final String assetType; + @SerializedName("asset_code") + protected final String assetCode; + @SerializedName("asset_issuer") + protected final String assetIssuer; + @SerializedName("limit") + protected final String limit; + + ChangeTrustOperationResponse(KeyPair trustor, KeyPair trustee, String assetType, String assetCode, String assetIssuer, String limit) { + this.trustor = trustor; + this.trustee = trustee; + this.assetType = assetType; + this.assetCode = assetCode; + this.assetIssuer = assetIssuer; + this.limit = limit; + } + + public KeyPair getTrustor() { + return trustor; + } + + public KeyPair getTrustee() { + return trustee; + } + + public String getLimit() { + return limit; + } + + public Asset getAsset() { + if (assetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(assetIssuer); + return Asset.createNonNativeAsset(assetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/CreateAccountOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/CreateAccountOperationResponse.java new file mode 100644 index 0000000000..c7764b04a7 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/CreateAccountOperationResponse.java @@ -0,0 +1,38 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.KeyPair; + +/** + * Represents CreateAccount operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class CreateAccountOperationResponse extends OperationResponse { + @SerializedName("account") + protected final KeyPair account; + @SerializedName("funder") + protected final KeyPair funder; + @SerializedName("starting_balance") + protected final String startingBalance; + + CreateAccountOperationResponse(KeyPair funder, String startingBalance, KeyPair account) { + this.funder = funder; + this.startingBalance = startingBalance; + this.account = account; + } + + public KeyPair getAccount() { + return account; + } + + public String getStartingBalance() { + return startingBalance; + } + + public KeyPair getFunder() { + return funder; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/CreatePassiveOfferOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/CreatePassiveOfferOperationResponse.java new file mode 100644 index 0000000000..74b2b6ce9d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/CreatePassiveOfferOperationResponse.java @@ -0,0 +1,80 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +/** + * Represents CreatePassiveOffer operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class CreatePassiveOfferOperationResponse extends OperationResponse { + @SerializedName("offer_id") + protected final Integer offerId; + @SerializedName("amount") + protected final String amount; + // Price is not implemented yet in horizon + @SerializedName("price") + protected final String price; + + + @SerializedName("buying_asset_type") + protected final String buyingAssetType; + @SerializedName("buying_asset_code") + protected final String buyingAssetCode; + @SerializedName("buying_asset_issuer") + protected final String buyingAssetIssuer; + + @SerializedName("selling_asset_type") + protected final String sellingAssetType; + @SerializedName("selling_asset_code") + protected final String sellingAssetCode; + @SerializedName("selling_asset_issuer") + protected final String sellingAssetIssuer; + + CreatePassiveOfferOperationResponse(Integer offerId, String amount, String price, String buyingAssetType, String buyingAssetCode, String buyingAssetIssuer, String sellingAssetType, String sellingAssetCode, String sellingAssetIssuer) { + this.offerId = offerId; + this.amount = amount; + this.price = price; + this.buyingAssetType = buyingAssetType; + this.buyingAssetCode = buyingAssetCode; + this.buyingAssetIssuer = buyingAssetIssuer; + this.sellingAssetType = sellingAssetType; + this.sellingAssetCode = sellingAssetCode; + this.sellingAssetIssuer = sellingAssetIssuer; + } + + public Integer getOfferId() { + return offerId; + } + + public String getAmount() { + return amount; + } + + public String getPrice() { + return price; + } + + public Asset getBuyingAsset() { + if (buyingAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(buyingAssetIssuer); + return Asset.createNonNativeAsset(buyingAssetCode, issuer); + } + } + + public Asset getSellingAsset() { + if (sellingAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(sellingAssetIssuer); + return Asset.createNonNativeAsset(sellingAssetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/InflationOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/InflationOperationResponse.java new file mode 100644 index 0000000000..c0054d224a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/InflationOperationResponse.java @@ -0,0 +1,10 @@ +package org.stellar.sdk.responses.operations; + +/** + * Represents Inflation operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class InflationOperationResponse extends OperationResponse { +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/ManageDataOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/ManageDataOperationResponse.java new file mode 100644 index 0000000000..93834113da --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/ManageDataOperationResponse.java @@ -0,0 +1,29 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +/** + * Represents ManageDataoperation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class ManageDataOperationResponse extends OperationResponse { + @SerializedName("name") + protected final String name; + @SerializedName("value") + protected final String value; + + ManageDataOperationResponse(String name, String value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public String getValue() { + return value; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/ManageOfferOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/ManageOfferOperationResponse.java new file mode 100644 index 0000000000..e0da51b153 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/ManageOfferOperationResponse.java @@ -0,0 +1,80 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +/** + * Represents ManageOffer operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class ManageOfferOperationResponse extends OperationResponse { + @SerializedName("offer_id") + protected final Integer offerId; + @SerializedName("amount") + protected final String amount; + // Price is not implemented yet in horizon + @SerializedName("price") + protected final String price; + + + @SerializedName("buying_asset_type") + protected final String buyingAssetType; + @SerializedName("buying_asset_code") + protected final String buyingAssetCode; + @SerializedName("buying_asset_issuer") + protected final String buyingAssetIssuer; + + @SerializedName("selling_asset_type") + protected final String sellingAssetType; + @SerializedName("selling_asset_code") + protected final String sellingAssetCode; + @SerializedName("selling_asset_issuer") + protected final String sellingAssetIssuer; + + ManageOfferOperationResponse(Integer offerId, String amount, String price, String buyingAssetType, String buyingAssetCode, String buyingAssetIssuer, String sellingAssetType, String sellingAssetCode, String sellingAssetIssuer) { + this.offerId = offerId; + this.amount = amount; + this.price = price; + this.buyingAssetType = buyingAssetType; + this.buyingAssetCode = buyingAssetCode; + this.buyingAssetIssuer = buyingAssetIssuer; + this.sellingAssetType = sellingAssetType; + this.sellingAssetCode = sellingAssetCode; + this.sellingAssetIssuer = sellingAssetIssuer; + } + + public Integer getOfferId() { + return offerId; + } + + public String getAmount() { + return amount; + } + + public String getPrice() { + return price; + } + + public Asset getBuyingAsset() { + if (buyingAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(buyingAssetIssuer); + return Asset.createNonNativeAsset(buyingAssetCode, issuer); + } + } + + public Asset getSellingAsset() { + if (sellingAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(sellingAssetIssuer); + return Asset.createNonNativeAsset(sellingAssetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/OperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/OperationResponse.java new file mode 100644 index 0000000000..3598283801 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/OperationResponse.java @@ -0,0 +1,121 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.KeyPair; +import org.stellar.sdk.responses.Link; +import org.stellar.sdk.responses.Response; + +/** + * Abstract class for operation responses. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public abstract class OperationResponse extends Response { + @SerializedName("id") + protected Long id; + @SerializedName("source_account") + protected KeyPair sourceAccount; + @SerializedName("paging_token") + protected String pagingToken; + @SerializedName("created_at") + protected String createdAt; + @SerializedName("transaction_hash") + protected String transactionHash; + @SerializedName("type") + protected String type; + @SerializedName("_links") + private Links links; + + public Long getId() { + return id; + } + + public KeyPair getSourceAccount() { + return sourceAccount; + } + + public String getPagingToken() { + return pagingToken; + } + + /** + *

Returns operation type. Possible types:

+ *
    + *
  • create_account
  • + *
  • payment
  • + *
  • allow_trust
  • + *
  • change_trust
  • + *
  • set_options
  • + *
  • account_merge
  • + *
  • manage_offer
  • + *
  • path_payment
  • + *
  • create_passive_offer
  • + *
  • inflation
  • + *
  • manage_data
  • + *
+ */ + public String getType() { + return type; + } + + public String getCreatedAt() { + return createdAt; + } + + /** + * Returns transaction hash of transaction this operation belongs to. + */ + public String getTransactionHash() { + return transactionHash; + } + + public Links getLinks() { + return links; + } + + /** + * Represents operation links. + */ + public static class Links { + @SerializedName("effects") + private final Link effects; + @SerializedName("precedes") + private final Link precedes; + @SerializedName("self") + private final Link self; + @SerializedName("succeeds") + private final Link succeeds; + @SerializedName("transaction") + private final Link transaction; + + public Links(Link effects, Link precedes, Link self, Link succeeds, Link transaction) { + this.effects = effects; + this.precedes = precedes; + this.self = self; + this.succeeds = succeeds; + this.transaction = transaction; + } + + public Link getEffects() { + return effects; + } + + public Link getPrecedes() { + return precedes; + } + + public Link getSelf() { + return self; + } + + public Link getSucceeds() { + return succeeds; + } + + public Link getTransaction() { + return transaction; + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/PathPaymentOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/PathPaymentOperationResponse.java new file mode 100644 index 0000000000..3b9882eb9f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/PathPaymentOperationResponse.java @@ -0,0 +1,85 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +/** + * Represents PathPayment operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class PathPaymentOperationResponse extends OperationResponse { + @SerializedName("amount") + protected final String amount; + @SerializedName("source_max") + protected final String sourceMax; + @SerializedName("from") + protected final KeyPair from; + @SerializedName("to") + protected final KeyPair to; + + @SerializedName("asset_type") + protected final String assetType; + @SerializedName("asset_code") + protected final String assetCode; + @SerializedName("asset_issuer") + protected final String assetIssuer; + + @SerializedName("source_asset_type") + protected final String sourceAssetType; + @SerializedName("source_asset_code") + protected final String sourceAssetCode; + @SerializedName("source_asset_issuer") + protected final String sourceAssetIssuer; + + public PathPaymentOperationResponse(String amount, String sourceMax, KeyPair from, KeyPair to, String assetType, String assetCode, String assetIssuer, String sourceAssetType, String sourceAssetCode, String sourceAssetIssuer) { + this.amount = amount; + this.sourceMax = sourceMax; + this.from = from; + this.to = to; + this.assetType = assetType; + this.assetCode = assetCode; + this.assetIssuer = assetIssuer; + this.sourceAssetType = sourceAssetType; + this.sourceAssetCode = sourceAssetCode; + this.sourceAssetIssuer = sourceAssetIssuer; + } + + public String getAmount() { + return amount; + } + + public String getSourceMax() { + return sourceMax; + } + + public KeyPair getFrom() { + return from; + } + + public KeyPair getTo() { + return to; + } + + public Asset getAsset() { + if (assetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(assetIssuer); + return Asset.createNonNativeAsset(assetCode, issuer); + } + } + + public Asset getSourceAsset() { + if (sourceAssetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(sourceAssetIssuer); + return Asset.createNonNativeAsset(sourceAssetCode, issuer); + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/PaymentOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/PaymentOperationResponse.java new file mode 100644 index 0000000000..623d5257e0 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/PaymentOperationResponse.java @@ -0,0 +1,58 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.Asset; +import org.stellar.sdk.AssetTypeNative; +import org.stellar.sdk.KeyPair; + +/** + * Represents Payment operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class PaymentOperationResponse extends OperationResponse { + @SerializedName("amount") + protected final String amount; + @SerializedName("asset_type") + protected final String assetType; + @SerializedName("asset_code") + protected final String assetCode; + @SerializedName("asset_issuer") + protected final String assetIssuer; + @SerializedName("from") + protected final KeyPair from; + @SerializedName("to") + protected final KeyPair to; + + PaymentOperationResponse(String amount, String assetType, String assetCode, String assetIssuer, KeyPair from, KeyPair to) { + this.amount = amount; + this.assetType = assetType; + this.assetCode = assetCode; + this.assetIssuer = assetIssuer; + this.from = from; + this.to = to; + } + + public String getAmount() { + return amount; + } + + public Asset getAsset() { + if (assetType.equals("native")) { + return new AssetTypeNative(); + } else { + KeyPair issuer = KeyPair.fromAccountId(assetIssuer); + return Asset.createNonNativeAsset(assetCode, issuer); + } + } + + public KeyPair getFrom() { + return from; + } + + public KeyPair getTo() { + return to; + } +} diff --git a/app/src/main/java/org/stellar/sdk/responses/operations/SetOptionsOperationResponse.java b/app/src/main/java/org/stellar/sdk/responses/operations/SetOptionsOperationResponse.java new file mode 100644 index 0000000000..b995739e90 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/responses/operations/SetOptionsOperationResponse.java @@ -0,0 +1,95 @@ +package org.stellar.sdk.responses.operations; + +import com.google.gson.annotations.SerializedName; + +import org.stellar.sdk.KeyPair; + +/** + * Represents SetOptions operation response. + * @see Operation documentation + * @see org.stellar.sdk.requests.OperationsRequestBuilder + * @see org.stellar.sdk.Server#operations() + */ +public class SetOptionsOperationResponse extends OperationResponse { + @SerializedName("low_threshold") + protected final Integer lowThreshold; + @SerializedName("med_threshold") + protected final Integer medThreshold; + @SerializedName("high_threshold") + protected final Integer highThreshold; + @SerializedName("inflation_dest") + protected final KeyPair inflationDestination; + @SerializedName("home_domain") + protected final String homeDomain; + @SerializedName("signer_key") + protected final String signerKey; + @SerializedName("signer_weight") + protected final Integer signerWeight; + @SerializedName("master_key_weight") + protected final Integer masterKeyWeight; + @SerializedName("clear_flags_s") + protected final String[] clearFlags; + @SerializedName("set_flags_s") + protected final String[] setFlags; + + SetOptionsOperationResponse(Integer lowThreshold, Integer medThreshold, Integer highThreshold, KeyPair inflationDestination, String homeDomain, String signerKey, Integer signerWeight, Integer masterKeyWeight, String[] clearFlags, String[] setFlags) { + this.lowThreshold = lowThreshold; + this.medThreshold = medThreshold; + this.highThreshold = highThreshold; + this.inflationDestination = inflationDestination; + this.homeDomain = homeDomain; + this.signerKey = signerKey; + this.signerWeight = signerWeight; + this.masterKeyWeight = masterKeyWeight; + this.clearFlags = clearFlags; + this.setFlags = setFlags; + } + + public Integer getLowThreshold() { + return lowThreshold; + } + + public Integer getMedThreshold() { + return medThreshold; + } + + public Integer getHighThreshold() { + return highThreshold; + } + + public KeyPair getInflationDestination() { + return inflationDestination; + } + + public String getHomeDomain() { + return homeDomain; + } + + public String getSignerKey() { + return signerKey; + } + + /** + * @deprecated Use {@link SetOptionsOperationResponse#getSignerKey()} + * @return + */ + public KeyPair getSigner() { + return KeyPair.fromAccountId(signerKey); + } + + public Integer getSignerWeight() { + return signerWeight; + } + + public Integer getMasterKeyWeight() { + return masterKeyWeight; + } + + public String[] getClearFlags() { + return clearFlags; + } + + public String[] getSetFlags() { + return setFlags; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AccountEntry.java b/app/src/main/java/org/stellar/sdk/xdr/AccountEntry.java new file mode 100644 index 0000000000..2748f4df42 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AccountEntry.java @@ -0,0 +1,263 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct AccountEntry +// { +// AccountID accountID; // master public key for this account +// int64 balance; // in stroops +// SequenceNumber seqNum; // last sequence number used for this account +// uint32 numSubEntries; // number of sub-entries this account has +// // drives the reserve +// AccountID* inflationDest; // Account to vote for during inflation +// uint32 flags; // see AccountFlags +// +// string32 homeDomain; // can be used for reverse federation and memo lookup +// +// // fields used for signatures +// // thresholds stores unsigned bytes: [weight of master|low|medium|high] +// Thresholds thresholds; +// +// Signer signers<20>; // possible signers for this account +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// case 1: +// struct +// { +// Liabilities liabilities; +// +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// } v1; +// } +// ext; +// }; + +// =========================================================================== +public class AccountEntry { + public AccountEntry () {} + private AccountID accountID; + public AccountID getAccountID() { + return this.accountID; + } + public void setAccountID(AccountID value) { + this.accountID = value; + } + private Int64 balance; + public Int64 getBalance() { + return this.balance; + } + public void setBalance(Int64 value) { + this.balance = value; + } + private SequenceNumber seqNum; + public SequenceNumber getSeqNum() { + return this.seqNum; + } + public void setSeqNum(SequenceNumber value) { + this.seqNum = value; + } + private Uint32 numSubEntries; + public Uint32 getNumSubEntries() { + return this.numSubEntries; + } + public void setNumSubEntries(Uint32 value) { + this.numSubEntries = value; + } + private AccountID inflationDest; + public AccountID getInflationDest() { + return this.inflationDest; + } + public void setInflationDest(AccountID value) { + this.inflationDest = value; + } + private Uint32 flags; + public Uint32 getFlags() { + return this.flags; + } + public void setFlags(Uint32 value) { + this.flags = value; + } + private String32 homeDomain; + public String32 getHomeDomain() { + return this.homeDomain; + } + public void setHomeDomain(String32 value) { + this.homeDomain = value; + } + private Thresholds thresholds; + public Thresholds getThresholds() { + return this.thresholds; + } + public void setThresholds(Thresholds value) { + this.thresholds = value; + } + private Signer[] signers; + public Signer[] getSigners() { + return this.signers; + } + public void setSigners(Signer[] value) { + this.signers = value; + } + private AccountEntryExt ext; + public AccountEntryExt getExt() { + return this.ext; + } + public void setExt(AccountEntryExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, AccountEntry encodedAccountEntry) throws IOException{ + AccountID.encode(stream, encodedAccountEntry.accountID); + Int64.encode(stream, encodedAccountEntry.balance); + SequenceNumber.encode(stream, encodedAccountEntry.seqNum); + Uint32.encode(stream, encodedAccountEntry.numSubEntries); + if (encodedAccountEntry.inflationDest != null) { + stream.writeInt(1); + AccountID.encode(stream, encodedAccountEntry.inflationDest); + } else { + stream.writeInt(0); + } + Uint32.encode(stream, encodedAccountEntry.flags); + String32.encode(stream, encodedAccountEntry.homeDomain); + Thresholds.encode(stream, encodedAccountEntry.thresholds); + int signerssize = encodedAccountEntry.getSigners().length; + stream.writeInt(signerssize); + for (int i = 0; i < signerssize; i++) { + Signer.encode(stream, encodedAccountEntry.signers[i]); + } + AccountEntryExt.encode(stream, encodedAccountEntry.ext); + } + public static AccountEntry decode(XdrDataInputStream stream) throws IOException { + AccountEntry decodedAccountEntry = new AccountEntry(); + decodedAccountEntry.accountID = AccountID.decode(stream); + decodedAccountEntry.balance = Int64.decode(stream); + decodedAccountEntry.seqNum = SequenceNumber.decode(stream); + decodedAccountEntry.numSubEntries = Uint32.decode(stream); + int inflationDestPresent = stream.readInt(); + if (inflationDestPresent != 0) { + decodedAccountEntry.inflationDest = AccountID.decode(stream); + } + decodedAccountEntry.flags = Uint32.decode(stream); + decodedAccountEntry.homeDomain = String32.decode(stream); + decodedAccountEntry.thresholds = Thresholds.decode(stream); + int signerssize = stream.readInt(); + decodedAccountEntry.signers = new Signer[signerssize]; + for (int i = 0; i < signerssize; i++) { + decodedAccountEntry.signers[i] = Signer.decode(stream); + } + decodedAccountEntry.ext = AccountEntryExt.decode(stream); + return decodedAccountEntry; + } + + public static class AccountEntryExt { + public AccountEntryExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + private AccountEntryV1 v1; + public AccountEntryV1 getV1() { + return this.v1; + } + public void setV1(AccountEntryV1 value) { + this.v1 = value; + } + public static void encode(XdrDataOutputStream stream, AccountEntryExt encodedAccountEntryExt) throws IOException { + stream.writeInt(encodedAccountEntryExt.getDiscriminant().intValue()); + switch (encodedAccountEntryExt.getDiscriminant()) { + case 0: + break; + case 1: + AccountEntryV1.encode(stream, encodedAccountEntryExt.v1); + break; + } + } + public static AccountEntryExt decode(XdrDataInputStream stream) throws IOException { + AccountEntryExt decodedAccountEntryExt = new AccountEntryExt(); + Integer discriminant = stream.readInt(); + decodedAccountEntryExt.setDiscriminant(discriminant); + switch (decodedAccountEntryExt.getDiscriminant()) { + case 0: + break; + case 1: + decodedAccountEntryExt.v1 = AccountEntryV1.decode(stream); + break; + } + return decodedAccountEntryExt; + } + + public static class AccountEntryV1 { + public AccountEntryV1 () {} + private Liabilities liabilities; + public Liabilities getLiabilities() { + return this.liabilities; + } + public void setLiabilities(Liabilities value) { + this.liabilities = value; + } + private AccountEntryV1Ext ext; + public AccountEntryV1Ext getExt() { + return this.ext; + } + public void setExt(AccountEntryV1Ext value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, AccountEntryV1 encodedAccountEntryV1) throws IOException{ + Liabilities.encode(stream, encodedAccountEntryV1.liabilities); + AccountEntryV1Ext.encode(stream, encodedAccountEntryV1.ext); + } + public static AccountEntryV1 decode(XdrDataInputStream stream) throws IOException { + AccountEntryV1 decodedAccountEntryV1 = new AccountEntryV1(); + decodedAccountEntryV1.liabilities = Liabilities.decode(stream); + decodedAccountEntryV1.ext = AccountEntryV1Ext.decode(stream); + return decodedAccountEntryV1; + } + + public static class AccountEntryV1Ext { + public AccountEntryV1Ext () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, AccountEntryV1Ext encodedAccountEntryV1Ext) throws IOException { + stream.writeInt(encodedAccountEntryV1Ext.getDiscriminant().intValue()); + switch (encodedAccountEntryV1Ext.getDiscriminant()) { + case 0: + break; + } + } + public static AccountEntryV1Ext decode(XdrDataInputStream stream) throws IOException { + AccountEntryV1Ext decodedAccountEntryV1Ext = new AccountEntryV1Ext(); + Integer discriminant = stream.readInt(); + decodedAccountEntryV1Ext.setDiscriminant(discriminant); + switch (decodedAccountEntryV1Ext.getDiscriminant()) { + case 0: + break; + } + return decodedAccountEntryV1Ext; + } + + } + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AccountFlags.java b/app/src/main/java/org/stellar/sdk/xdr/AccountFlags.java new file mode 100644 index 0000000000..24002321ca --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AccountFlags.java @@ -0,0 +1,55 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum AccountFlags +// { // masks for each flag +// +// // Flags set on issuer accounts +// // TrustLines are created with authorized set to "false" requiring +// // the issuer to set it for each TrustLine +// AUTH_REQUIRED_FLAG = 0x1, +// // If set, the authorized flag in TrustLines can be cleared +// // otherwise, authorization cannot be revoked +// AUTH_REVOCABLE_FLAG = 0x2, +// // Once set, causes all AUTH_* flags to be read-only +// AUTH_IMMUTABLE_FLAG = 0x4 +// }; + +// =========================================================================== +public enum AccountFlags { + AUTH_REQUIRED_FLAG(1), + AUTH_REVOCABLE_FLAG(2), + AUTH_IMMUTABLE_FLAG(4), + ; + private int mValue; + + AccountFlags(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static AccountFlags decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 1: return AUTH_REQUIRED_FLAG; + case 2: return AUTH_REVOCABLE_FLAG; + case 4: return AUTH_IMMUTABLE_FLAG; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, AccountFlags value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AccountID.java b/app/src/main/java/org/stellar/sdk/xdr/AccountID.java new file mode 100644 index 0000000000..92d6e0a6bb --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AccountID.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef PublicKey AccountID; + +// =========================================================================== +public class AccountID { + private PublicKey AccountID; + public PublicKey getAccountID() { + return this.AccountID; + } + public void setAccountID(PublicKey value) { + this.AccountID = value; + } + public static void encode(XdrDataOutputStream stream, AccountID encodedAccountID) throws IOException { + PublicKey.encode(stream, encodedAccountID.AccountID); + } + public static AccountID decode(XdrDataInputStream stream) throws IOException { + AccountID decodedAccountID = new AccountID(); + decodedAccountID.AccountID = PublicKey.decode(stream); + return decodedAccountID; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AccountMergeResult.java b/app/src/main/java/org/stellar/sdk/xdr/AccountMergeResult.java new file mode 100644 index 0000000000..d7fb7fb92c --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AccountMergeResult.java @@ -0,0 +1,59 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union AccountMergeResult switch (AccountMergeResultCode code) +// { +// case ACCOUNT_MERGE_SUCCESS: +// int64 sourceAccountBalance; // how much got transfered from source account +// default: +// void; +// }; + +// =========================================================================== +public class AccountMergeResult { + public AccountMergeResult () {} + AccountMergeResultCode code; + public AccountMergeResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(AccountMergeResultCode value) { + this.code = value; + } + private Int64 sourceAccountBalance; + public Int64 getSourceAccountBalance() { + return this.sourceAccountBalance; + } + public void setSourceAccountBalance(Int64 value) { + this.sourceAccountBalance = value; + } + public static void encode(XdrDataOutputStream stream, AccountMergeResult encodedAccountMergeResult) throws IOException { + stream.writeInt(encodedAccountMergeResult.getDiscriminant().getValue()); + switch (encodedAccountMergeResult.getDiscriminant()) { + case ACCOUNT_MERGE_SUCCESS: + Int64.encode(stream, encodedAccountMergeResult.sourceAccountBalance); + break; + default: + break; + } + } + public static AccountMergeResult decode(XdrDataInputStream stream) throws IOException { + AccountMergeResult decodedAccountMergeResult = new AccountMergeResult(); + AccountMergeResultCode discriminant = AccountMergeResultCode.decode(stream); + decodedAccountMergeResult.setDiscriminant(discriminant); + switch (decodedAccountMergeResult.getDiscriminant()) { + case ACCOUNT_MERGE_SUCCESS: + decodedAccountMergeResult.sourceAccountBalance = Int64.decode(stream); + break; + default: + break; + } + return decodedAccountMergeResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AccountMergeResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/AccountMergeResultCode.java new file mode 100644 index 0000000000..76c5d7683f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AccountMergeResultCode.java @@ -0,0 +1,63 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum AccountMergeResultCode +// { +// // codes considered as "success" for the operation +// ACCOUNT_MERGE_SUCCESS = 0, +// // codes considered as "failure" for the operation +// ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself +// ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist +// ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set +// ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers +// ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed +// ACCOUNT_MERGE_DEST_FULL = -6 // can't add source balance to +// // destination balance +// }; + +// =========================================================================== +public enum AccountMergeResultCode { + ACCOUNT_MERGE_SUCCESS(0), + ACCOUNT_MERGE_MALFORMED(-1), + ACCOUNT_MERGE_NO_ACCOUNT(-2), + ACCOUNT_MERGE_IMMUTABLE_SET(-3), + ACCOUNT_MERGE_HAS_SUB_ENTRIES(-4), + ACCOUNT_MERGE_SEQNUM_TOO_FAR(-5), + ACCOUNT_MERGE_DEST_FULL(-6), + ; + private int mValue; + + AccountMergeResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static AccountMergeResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return ACCOUNT_MERGE_SUCCESS; + case -1: return ACCOUNT_MERGE_MALFORMED; + case -2: return ACCOUNT_MERGE_NO_ACCOUNT; + case -3: return ACCOUNT_MERGE_IMMUTABLE_SET; + case -4: return ACCOUNT_MERGE_HAS_SUB_ENTRIES; + case -5: return ACCOUNT_MERGE_SEQNUM_TOO_FAR; + case -6: return ACCOUNT_MERGE_DEST_FULL; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, AccountMergeResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AllowTrustOp.java b/app/src/main/java/org/stellar/sdk/xdr/AllowTrustOp.java new file mode 100644 index 0000000000..522e2b75c0 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AllowTrustOp.java @@ -0,0 +1,123 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct AllowTrustOp +// { +// AccountID trustor; +// union switch (AssetType type) +// { +// // ASSET_TYPE_NATIVE is not allowed +// case ASSET_TYPE_CREDIT_ALPHANUM4: +// opaque assetCode4[4]; +// +// case ASSET_TYPE_CREDIT_ALPHANUM12: +// opaque assetCode12[12]; +// +// // add other asset types here in the future +// } +// asset; +// +// bool authorize; +// }; + +// =========================================================================== +public class AllowTrustOp { + public AllowTrustOp () {} + private AccountID trustor; + public AccountID getTrustor() { + return this.trustor; + } + public void setTrustor(AccountID value) { + this.trustor = value; + } + private AllowTrustOpAsset asset; + public AllowTrustOpAsset getAsset() { + return this.asset; + } + public void setAsset(AllowTrustOpAsset value) { + this.asset = value; + } + private Boolean authorize; + public Boolean getAuthorize() { + return this.authorize; + } + public void setAuthorize(Boolean value) { + this.authorize = value; + } + public static void encode(XdrDataOutputStream stream, AllowTrustOp encodedAllowTrustOp) throws IOException{ + AccountID.encode(stream, encodedAllowTrustOp.trustor); + AllowTrustOpAsset.encode(stream, encodedAllowTrustOp.asset); + stream.writeInt(encodedAllowTrustOp.authorize ? 1 : 0); + } + public static AllowTrustOp decode(XdrDataInputStream stream) throws IOException { + AllowTrustOp decodedAllowTrustOp = new AllowTrustOp(); + decodedAllowTrustOp.trustor = AccountID.decode(stream); + decodedAllowTrustOp.asset = AllowTrustOpAsset.decode(stream); + decodedAllowTrustOp.authorize = stream.readInt() == 1 ? true : false; + return decodedAllowTrustOp; + } + + public static class AllowTrustOpAsset { + public AllowTrustOpAsset () {} + AssetType type; + public AssetType getDiscriminant() { + return this.type; + } + public void setDiscriminant(AssetType value) { + this.type = value; + } + private byte[] assetCode4; + public byte[] getAssetCode4() { + return this.assetCode4; + } + public void setAssetCode4(byte[] value) { + this.assetCode4 = value; + } + private byte[] assetCode12; + public byte[] getAssetCode12() { + return this.assetCode12; + } + public void setAssetCode12(byte[] value) { + this.assetCode12 = value; + } + public static void encode(XdrDataOutputStream stream, AllowTrustOpAsset encodedAllowTrustOpAsset) throws IOException { + stream.writeInt(encodedAllowTrustOpAsset.getDiscriminant().getValue()); + switch (encodedAllowTrustOpAsset.getDiscriminant()) { + case ASSET_TYPE_CREDIT_ALPHANUM4: + int assetCode4size = encodedAllowTrustOpAsset.assetCode4.length; + stream.write(encodedAllowTrustOpAsset.getAssetCode4(), 0, assetCode4size); + break; + case ASSET_TYPE_CREDIT_ALPHANUM12: + int assetCode12size = encodedAllowTrustOpAsset.assetCode12.length; + stream.write(encodedAllowTrustOpAsset.getAssetCode12(), 0, assetCode12size); + break; + } + } + public static AllowTrustOpAsset decode(XdrDataInputStream stream) throws IOException { + AllowTrustOpAsset decodedAllowTrustOpAsset = new AllowTrustOpAsset(); + AssetType discriminant = AssetType.decode(stream); + decodedAllowTrustOpAsset.setDiscriminant(discriminant); + switch (decodedAllowTrustOpAsset.getDiscriminant()) { + case ASSET_TYPE_CREDIT_ALPHANUM4: + int assetCode4size = 4; + decodedAllowTrustOpAsset.assetCode4 = new byte[assetCode4size]; + stream.read(decodedAllowTrustOpAsset.assetCode4, 0, assetCode4size); + break; + case ASSET_TYPE_CREDIT_ALPHANUM12: + int assetCode12size = 12; + decodedAllowTrustOpAsset.assetCode12 = new byte[assetCode12size]; + stream.read(decodedAllowTrustOpAsset.assetCode12, 0, assetCode12size); + break; + } + return decodedAllowTrustOpAsset; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AllowTrustResult.java b/app/src/main/java/org/stellar/sdk/xdr/AllowTrustResult.java new file mode 100644 index 0000000000..cc05837799 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AllowTrustResult.java @@ -0,0 +1,50 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union AllowTrustResult switch (AllowTrustResultCode code) +// { +// case ALLOW_TRUST_SUCCESS: +// void; +// default: +// void; +// }; + +// =========================================================================== +public class AllowTrustResult { + public AllowTrustResult () {} + AllowTrustResultCode code; + public AllowTrustResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(AllowTrustResultCode value) { + this.code = value; + } + public static void encode(XdrDataOutputStream stream, AllowTrustResult encodedAllowTrustResult) throws IOException { + stream.writeInt(encodedAllowTrustResult.getDiscriminant().getValue()); + switch (encodedAllowTrustResult.getDiscriminant()) { + case ALLOW_TRUST_SUCCESS: + break; + default: + break; + } + } + public static AllowTrustResult decode(XdrDataInputStream stream) throws IOException { + AllowTrustResult decodedAllowTrustResult = new AllowTrustResult(); + AllowTrustResultCode discriminant = AllowTrustResultCode.decode(stream); + decodedAllowTrustResult.setDiscriminant(discriminant); + switch (decodedAllowTrustResult.getDiscriminant()) { + case ALLOW_TRUST_SUCCESS: + break; + default: + break; + } + return decodedAllowTrustResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AllowTrustResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/AllowTrustResultCode.java new file mode 100644 index 0000000000..90ce88b22f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AllowTrustResultCode.java @@ -0,0 +1,60 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum AllowTrustResultCode +// { +// // codes considered as "success" for the operation +// ALLOW_TRUST_SUCCESS = 0, +// // codes considered as "failure" for the operation +// ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM +// ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline +// // source account does not require trust +// ALLOW_TRUST_TRUST_NOT_REQUIRED = -3, +// ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust, +// ALLOW_TRUST_SELF_NOT_ALLOWED = -5 // trusting self is not allowed +// }; + +// =========================================================================== +public enum AllowTrustResultCode { + ALLOW_TRUST_SUCCESS(0), + ALLOW_TRUST_MALFORMED(-1), + ALLOW_TRUST_NO_TRUST_LINE(-2), + ALLOW_TRUST_TRUST_NOT_REQUIRED(-3), + ALLOW_TRUST_CANT_REVOKE(-4), + ALLOW_TRUST_SELF_NOT_ALLOWED(-5), + ; + private int mValue; + + AllowTrustResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static AllowTrustResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return ALLOW_TRUST_SUCCESS; + case -1: return ALLOW_TRUST_MALFORMED; + case -2: return ALLOW_TRUST_NO_TRUST_LINE; + case -3: return ALLOW_TRUST_TRUST_NOT_REQUIRED; + case -4: return ALLOW_TRUST_CANT_REVOKE; + case -5: return ALLOW_TRUST_SELF_NOT_ALLOWED; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, AllowTrustResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Asset.java b/app/src/main/java/org/stellar/sdk/xdr/Asset.java new file mode 100644 index 0000000000..9834fa65cf --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Asset.java @@ -0,0 +1,149 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union Asset switch (AssetType type) +// { +// case ASSET_TYPE_NATIVE: // Not credit +// void; +// +// case ASSET_TYPE_CREDIT_ALPHANUM4: +// struct +// { +// opaque assetCode[4]; // 1 to 4 characters +// AccountID issuer; +// } alphaNum4; +// +// case ASSET_TYPE_CREDIT_ALPHANUM12: +// struct +// { +// opaque assetCode[12]; // 5 to 12 characters +// AccountID issuer; +// } alphaNum12; +// +// // add other asset types here in the future +// }; + +// =========================================================================== +public class Asset { + public Asset () {} + AssetType type; + public AssetType getDiscriminant() { + return this.type; + } + public void setDiscriminant(AssetType value) { + this.type = value; + } + private AssetAlphaNum4 alphaNum4; + public AssetAlphaNum4 getAlphaNum4() { + return this.alphaNum4; + } + public void setAlphaNum4(AssetAlphaNum4 value) { + this.alphaNum4 = value; + } + private AssetAlphaNum12 alphaNum12; + public AssetAlphaNum12 getAlphaNum12() { + return this.alphaNum12; + } + public void setAlphaNum12(AssetAlphaNum12 value) { + this.alphaNum12 = value; + } + public static void encode(XdrDataOutputStream stream, Asset encodedAsset) throws IOException { + stream.writeInt(encodedAsset.getDiscriminant().getValue()); + switch (encodedAsset.getDiscriminant()) { + case ASSET_TYPE_NATIVE: + break; + case ASSET_TYPE_CREDIT_ALPHANUM4: + AssetAlphaNum4.encode(stream, encodedAsset.alphaNum4); + break; + case ASSET_TYPE_CREDIT_ALPHANUM12: + AssetAlphaNum12.encode(stream, encodedAsset.alphaNum12); + break; + } + } + public static Asset decode(XdrDataInputStream stream) throws IOException { + Asset decodedAsset = new Asset(); + AssetType discriminant = AssetType.decode(stream); + decodedAsset.setDiscriminant(discriminant); + switch (decodedAsset.getDiscriminant()) { + case ASSET_TYPE_NATIVE: + break; + case ASSET_TYPE_CREDIT_ALPHANUM4: + decodedAsset.alphaNum4 = AssetAlphaNum4.decode(stream); + break; + case ASSET_TYPE_CREDIT_ALPHANUM12: + decodedAsset.alphaNum12 = AssetAlphaNum12.decode(stream); + break; + } + return decodedAsset; + } + + public static class AssetAlphaNum4 { + public AssetAlphaNum4 () {} + private byte[] assetCode; + public byte[] getAssetCode() { + return this.assetCode; + } + public void setAssetCode(byte[] value) { + this.assetCode = value; + } + private AccountID issuer; + public AccountID getIssuer() { + return this.issuer; + } + public void setIssuer(AccountID value) { + this.issuer = value; + } + public static void encode(XdrDataOutputStream stream, AssetAlphaNum4 encodedAssetAlphaNum4) throws IOException{ + int assetCodesize = encodedAssetAlphaNum4.assetCode.length; + stream.write(encodedAssetAlphaNum4.getAssetCode(), 0, assetCodesize); + AccountID.encode(stream, encodedAssetAlphaNum4.issuer); + } + public static AssetAlphaNum4 decode(XdrDataInputStream stream) throws IOException { + AssetAlphaNum4 decodedAssetAlphaNum4 = new AssetAlphaNum4(); + int assetCodesize = 4; + decodedAssetAlphaNum4.assetCode = new byte[assetCodesize]; + stream.read(decodedAssetAlphaNum4.assetCode, 0, assetCodesize); + decodedAssetAlphaNum4.issuer = AccountID.decode(stream); + return decodedAssetAlphaNum4; + } + + } + public static class AssetAlphaNum12 { + public AssetAlphaNum12 () {} + private byte[] assetCode; + public byte[] getAssetCode() { + return this.assetCode; + } + public void setAssetCode(byte[] value) { + this.assetCode = value; + } + private AccountID issuer; + public AccountID getIssuer() { + return this.issuer; + } + public void setIssuer(AccountID value) { + this.issuer = value; + } + public static void encode(XdrDataOutputStream stream, AssetAlphaNum12 encodedAssetAlphaNum12) throws IOException{ + int assetCodesize = encodedAssetAlphaNum12.assetCode.length; + stream.write(encodedAssetAlphaNum12.getAssetCode(), 0, assetCodesize); + AccountID.encode(stream, encodedAssetAlphaNum12.issuer); + } + public static AssetAlphaNum12 decode(XdrDataInputStream stream) throws IOException { + AssetAlphaNum12 decodedAssetAlphaNum12 = new AssetAlphaNum12(); + int assetCodesize = 12; + decodedAssetAlphaNum12.assetCode = new byte[assetCodesize]; + stream.read(decodedAssetAlphaNum12.assetCode, 0, assetCodesize); + decodedAssetAlphaNum12.issuer = AccountID.decode(stream); + return decodedAssetAlphaNum12; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AssetType.java b/app/src/main/java/org/stellar/sdk/xdr/AssetType.java new file mode 100644 index 0000000000..aee598523e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AssetType.java @@ -0,0 +1,48 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum AssetType +// { +// ASSET_TYPE_NATIVE = 0, +// ASSET_TYPE_CREDIT_ALPHANUM4 = 1, +// ASSET_TYPE_CREDIT_ALPHANUM12 = 2 +// }; + +// =========================================================================== +public enum AssetType { + ASSET_TYPE_NATIVE(0), + ASSET_TYPE_CREDIT_ALPHANUM4(1), + ASSET_TYPE_CREDIT_ALPHANUM12(2), + ; + private int mValue; + + AssetType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static AssetType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return ASSET_TYPE_NATIVE; + case 1: return ASSET_TYPE_CREDIT_ALPHANUM4; + case 2: return ASSET_TYPE_CREDIT_ALPHANUM12; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, AssetType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Auth.java b/app/src/main/java/org/stellar/sdk/xdr/Auth.java new file mode 100644 index 0000000000..cedb715cad --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Auth.java @@ -0,0 +1,36 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Auth +// { +// // Empty message, just to confirm +// // establishment of MAC keys. +// int unused; +// }; + +// =========================================================================== +public class Auth { + public Auth () {} + private Integer unused; + public Integer getUnused() { + return this.unused; + } + public void setUnused(Integer value) { + this.unused = value; + } + public static void encode(XdrDataOutputStream stream, Auth encodedAuth) throws IOException{ + stream.writeInt(encodedAuth.unused); + } + public static Auth decode(XdrDataInputStream stream) throws IOException { + Auth decodedAuth = new Auth(); + decodedAuth.unused = stream.readInt(); + return decodedAuth; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AuthCert.java b/app/src/main/java/org/stellar/sdk/xdr/AuthCert.java new file mode 100644 index 0000000000..d2aa04f041 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AuthCert.java @@ -0,0 +1,54 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct AuthCert +// { +// Curve25519Public pubkey; +// uint64 expiration; +// Signature sig; +// }; + +// =========================================================================== +public class AuthCert { + public AuthCert () {} + private Curve25519Public pubkey; + public Curve25519Public getPubkey() { + return this.pubkey; + } + public void setPubkey(Curve25519Public value) { + this.pubkey = value; + } + private Uint64 expiration; + public Uint64 getExpiration() { + return this.expiration; + } + public void setExpiration(Uint64 value) { + this.expiration = value; + } + private Signature sig; + public Signature getSig() { + return this.sig; + } + public void setSig(Signature value) { + this.sig = value; + } + public static void encode(XdrDataOutputStream stream, AuthCert encodedAuthCert) throws IOException{ + Curve25519Public.encode(stream, encodedAuthCert.pubkey); + Uint64.encode(stream, encodedAuthCert.expiration); + Signature.encode(stream, encodedAuthCert.sig); + } + public static AuthCert decode(XdrDataInputStream stream) throws IOException { + AuthCert decodedAuthCert = new AuthCert(); + decodedAuthCert.pubkey = Curve25519Public.decode(stream); + decodedAuthCert.expiration = Uint64.decode(stream); + decodedAuthCert.sig = Signature.decode(stream); + return decodedAuthCert; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/AuthenticatedMessage.java b/app/src/main/java/org/stellar/sdk/xdr/AuthenticatedMessage.java new file mode 100644 index 0000000000..fc22cf0464 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/AuthenticatedMessage.java @@ -0,0 +1,96 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union AuthenticatedMessage switch (uint32 v) +// { +// case 0: +// struct +// { +// uint64 sequence; +// StellarMessage message; +// HmacSha256Mac mac; +// } v0; +// }; + +// =========================================================================== +public class AuthenticatedMessage { + public AuthenticatedMessage () {} + Uint32 v; + public Uint32 getDiscriminant() { + return this.v; + } + public void setDiscriminant(Uint32 value) { + this.v = value; + } + private AuthenticatedMessageV0 v0; + public AuthenticatedMessageV0 getV0() { + return this.v0; + } + public void setV0(AuthenticatedMessageV0 value) { + this.v0 = value; + } + public static void encode(XdrDataOutputStream stream, AuthenticatedMessage encodedAuthenticatedMessage) throws IOException { + stream.writeInt(encodedAuthenticatedMessage.getDiscriminant().getUint32()); + switch (encodedAuthenticatedMessage.getDiscriminant().getUint32()) { + case 0: + AuthenticatedMessageV0.encode(stream, encodedAuthenticatedMessage.v0); + break; + } + } + public static AuthenticatedMessage decode(XdrDataInputStream stream) throws IOException { + AuthenticatedMessage decodedAuthenticatedMessage = new AuthenticatedMessage(); + Uint32 discriminant = Uint32.decode(stream); + decodedAuthenticatedMessage.setDiscriminant(discriminant); + switch (decodedAuthenticatedMessage.getDiscriminant().getUint32()) { + case 0: + decodedAuthenticatedMessage.v0 = AuthenticatedMessageV0.decode(stream); + break; + } + return decodedAuthenticatedMessage; + } + + public static class AuthenticatedMessageV0 { + public AuthenticatedMessageV0 () {} + private Uint64 sequence; + public Uint64 getSequence() { + return this.sequence; + } + public void setSequence(Uint64 value) { + this.sequence = value; + } + private StellarMessage message; + public StellarMessage getMessage() { + return this.message; + } + public void setMessage(StellarMessage value) { + this.message = value; + } + private HmacSha256Mac mac; + public HmacSha256Mac getMac() { + return this.mac; + } + public void setMac(HmacSha256Mac value) { + this.mac = value; + } + public static void encode(XdrDataOutputStream stream, AuthenticatedMessageV0 encodedAuthenticatedMessageV0) throws IOException{ + Uint64.encode(stream, encodedAuthenticatedMessageV0.sequence); + StellarMessage.encode(stream, encodedAuthenticatedMessageV0.message); + HmacSha256Mac.encode(stream, encodedAuthenticatedMessageV0.mac); + } + public static AuthenticatedMessageV0 decode(XdrDataInputStream stream) throws IOException { + AuthenticatedMessageV0 decodedAuthenticatedMessageV0 = new AuthenticatedMessageV0(); + decodedAuthenticatedMessageV0.sequence = Uint64.decode(stream); + decodedAuthenticatedMessageV0.message = StellarMessage.decode(stream); + decodedAuthenticatedMessageV0.mac = HmacSha256Mac.decode(stream); + return decodedAuthenticatedMessageV0; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/BucketEntry.java b/app/src/main/java/org/stellar/sdk/xdr/BucketEntry.java new file mode 100644 index 0000000000..d6d303ddbe --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/BucketEntry.java @@ -0,0 +1,69 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union BucketEntry switch (BucketEntryType type) +// { +// case LIVEENTRY: +// LedgerEntry liveEntry; +// +// case DEADENTRY: +// LedgerKey deadEntry; +// }; + +// =========================================================================== +public class BucketEntry { + public BucketEntry () {} + BucketEntryType type; + public BucketEntryType getDiscriminant() { + return this.type; + } + public void setDiscriminant(BucketEntryType value) { + this.type = value; + } + private LedgerEntry liveEntry; + public LedgerEntry getLiveEntry() { + return this.liveEntry; + } + public void setLiveEntry(LedgerEntry value) { + this.liveEntry = value; + } + private LedgerKey deadEntry; + public LedgerKey getDeadEntry() { + return this.deadEntry; + } + public void setDeadEntry(LedgerKey value) { + this.deadEntry = value; + } + public static void encode(XdrDataOutputStream stream, BucketEntry encodedBucketEntry) throws IOException { + stream.writeInt(encodedBucketEntry.getDiscriminant().getValue()); + switch (encodedBucketEntry.getDiscriminant()) { + case LIVEENTRY: + LedgerEntry.encode(stream, encodedBucketEntry.liveEntry); + break; + case DEADENTRY: + LedgerKey.encode(stream, encodedBucketEntry.deadEntry); + break; + } + } + public static BucketEntry decode(XdrDataInputStream stream) throws IOException { + BucketEntry decodedBucketEntry = new BucketEntry(); + BucketEntryType discriminant = BucketEntryType.decode(stream); + decodedBucketEntry.setDiscriminant(discriminant); + switch (decodedBucketEntry.getDiscriminant()) { + case LIVEENTRY: + decodedBucketEntry.liveEntry = LedgerEntry.decode(stream); + break; + case DEADENTRY: + decodedBucketEntry.deadEntry = LedgerKey.decode(stream); + break; + } + return decodedBucketEntry; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/BucketEntryType.java b/app/src/main/java/org/stellar/sdk/xdr/BucketEntryType.java new file mode 100644 index 0000000000..daffd7fb3e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/BucketEntryType.java @@ -0,0 +1,45 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum BucketEntryType +// { +// LIVEENTRY = 0, +// DEADENTRY = 1 +// }; + +// =========================================================================== +public enum BucketEntryType { + LIVEENTRY(0), + DEADENTRY(1), + ; + private int mValue; + + BucketEntryType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static BucketEntryType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return LIVEENTRY; + case 1: return DEADENTRY; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, BucketEntryType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceOp.java b/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceOp.java new file mode 100644 index 0000000000..a9c53d9e6a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceOp.java @@ -0,0 +1,34 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct BumpSequenceOp +// { +// SequenceNumber bumpTo; +// }; + +// =========================================================================== +public class BumpSequenceOp { + public BumpSequenceOp () {} + private SequenceNumber bumpTo; + public SequenceNumber getBumpTo() { + return this.bumpTo; + } + public void setBumpTo(SequenceNumber value) { + this.bumpTo = value; + } + public static void encode(XdrDataOutputStream stream, BumpSequenceOp encodedBumpSequenceOp) throws IOException{ + SequenceNumber.encode(stream, encodedBumpSequenceOp.bumpTo); + } + public static BumpSequenceOp decode(XdrDataInputStream stream) throws IOException { + BumpSequenceOp decodedBumpSequenceOp = new BumpSequenceOp(); + decodedBumpSequenceOp.bumpTo = SequenceNumber.decode(stream); + return decodedBumpSequenceOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceResult.java b/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceResult.java new file mode 100644 index 0000000000..3c0267fc89 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceResult.java @@ -0,0 +1,50 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union BumpSequenceResult switch (BumpSequenceResultCode code) +// { +// case BUMP_SEQUENCE_SUCCESS: +// void; +// default: +// void; +// }; + +// =========================================================================== +public class BumpSequenceResult { + public BumpSequenceResult () {} + BumpSequenceResultCode code; + public BumpSequenceResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(BumpSequenceResultCode value) { + this.code = value; + } + public static void encode(XdrDataOutputStream stream, BumpSequenceResult encodedBumpSequenceResult) throws IOException { + stream.writeInt(encodedBumpSequenceResult.getDiscriminant().getValue()); + switch (encodedBumpSequenceResult.getDiscriminant()) { + case BUMP_SEQUENCE_SUCCESS: + break; + default: + break; + } + } + public static BumpSequenceResult decode(XdrDataInputStream stream) throws IOException { + BumpSequenceResult decodedBumpSequenceResult = new BumpSequenceResult(); + BumpSequenceResultCode discriminant = BumpSequenceResultCode.decode(stream); + decodedBumpSequenceResult.setDiscriminant(discriminant); + switch (decodedBumpSequenceResult.getDiscriminant()) { + case BUMP_SEQUENCE_SUCCESS: + break; + default: + break; + } + return decodedBumpSequenceResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceResultCode.java new file mode 100644 index 0000000000..4007708cdb --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/BumpSequenceResultCode.java @@ -0,0 +1,47 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum BumpSequenceResultCode +// { +// // codes considered as "success" for the operation +// BUMP_SEQUENCE_SUCCESS = 0, +// // codes considered as "failure" for the operation +// BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds +// }; + +// =========================================================================== +public enum BumpSequenceResultCode { + BUMP_SEQUENCE_SUCCESS(0), + BUMP_SEQUENCE_BAD_SEQ(-1), + ; + private int mValue; + + BumpSequenceResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static BumpSequenceResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return BUMP_SEQUENCE_SUCCESS; + case -1: return BUMP_SEQUENCE_BAD_SEQ; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, BumpSequenceResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustOp.java b/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustOp.java new file mode 100644 index 0000000000..09520a1cf3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustOp.java @@ -0,0 +1,46 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct ChangeTrustOp +// { +// Asset line; +// +// // if limit is set to 0, deletes the trust line +// int64 limit; +// }; + +// =========================================================================== +public class ChangeTrustOp { + public ChangeTrustOp () {} + private Asset line; + public Asset getLine() { + return this.line; + } + public void setLine(Asset value) { + this.line = value; + } + private Int64 limit; + public Int64 getLimit() { + return this.limit; + } + public void setLimit(Int64 value) { + this.limit = value; + } + public static void encode(XdrDataOutputStream stream, ChangeTrustOp encodedChangeTrustOp) throws IOException{ + Asset.encode(stream, encodedChangeTrustOp.line); + Int64.encode(stream, encodedChangeTrustOp.limit); + } + public static ChangeTrustOp decode(XdrDataInputStream stream) throws IOException { + ChangeTrustOp decodedChangeTrustOp = new ChangeTrustOp(); + decodedChangeTrustOp.line = Asset.decode(stream); + decodedChangeTrustOp.limit = Int64.decode(stream); + return decodedChangeTrustOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustResult.java b/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustResult.java new file mode 100644 index 0000000000..a1192257b8 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustResult.java @@ -0,0 +1,50 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union ChangeTrustResult switch (ChangeTrustResultCode code) +// { +// case CHANGE_TRUST_SUCCESS: +// void; +// default: +// void; +// }; + +// =========================================================================== +public class ChangeTrustResult { + public ChangeTrustResult () {} + ChangeTrustResultCode code; + public ChangeTrustResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(ChangeTrustResultCode value) { + this.code = value; + } + public static void encode(XdrDataOutputStream stream, ChangeTrustResult encodedChangeTrustResult) throws IOException { + stream.writeInt(encodedChangeTrustResult.getDiscriminant().getValue()); + switch (encodedChangeTrustResult.getDiscriminant()) { + case CHANGE_TRUST_SUCCESS: + break; + default: + break; + } + } + public static ChangeTrustResult decode(XdrDataInputStream stream) throws IOException { + ChangeTrustResult decodedChangeTrustResult = new ChangeTrustResult(); + ChangeTrustResultCode discriminant = ChangeTrustResultCode.decode(stream); + decodedChangeTrustResult.setDiscriminant(discriminant); + switch (decodedChangeTrustResult.getDiscriminant()) { + case CHANGE_TRUST_SUCCESS: + break; + default: + break; + } + return decodedChangeTrustResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustResultCode.java new file mode 100644 index 0000000000..4b3b1c87f4 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ChangeTrustResultCode.java @@ -0,0 +1,61 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum ChangeTrustResultCode +// { +// // codes considered as "success" for the operation +// CHANGE_TRUST_SUCCESS = 0, +// // codes considered as "failure" for the operation +// CHANGE_TRUST_MALFORMED = -1, // bad input +// CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer +// CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance +// // cannot create with a limit of 0 +// CHANGE_TRUST_LOW_RESERVE = +// -4, // not enough funds to create a new trust line, +// CHANGE_TRUST_SELF_NOT_ALLOWED = -5 // trusting self is not allowed +// }; + +// =========================================================================== +public enum ChangeTrustResultCode { + CHANGE_TRUST_SUCCESS(0), + CHANGE_TRUST_MALFORMED(-1), + CHANGE_TRUST_NO_ISSUER(-2), + CHANGE_TRUST_INVALID_LIMIT(-3), + CHANGE_TRUST_LOW_RESERVE(-4), + CHANGE_TRUST_SELF_NOT_ALLOWED(-5), + ; + private int mValue; + + ChangeTrustResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static ChangeTrustResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return CHANGE_TRUST_SUCCESS; + case -1: return CHANGE_TRUST_MALFORMED; + case -2: return CHANGE_TRUST_NO_ISSUER; + case -3: return CHANGE_TRUST_INVALID_LIMIT; + case -4: return CHANGE_TRUST_LOW_RESERVE; + case -5: return CHANGE_TRUST_SELF_NOT_ALLOWED; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, ChangeTrustResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ClaimOfferAtom.java b/app/src/main/java/org/stellar/sdk/xdr/ClaimOfferAtom.java new file mode 100644 index 0000000000..c0837b2e0a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ClaimOfferAtom.java @@ -0,0 +1,89 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct ClaimOfferAtom +// { +// // emitted to identify the offer +// AccountID sellerID; // Account that owns the offer +// uint64 offerID; +// +// // amount and asset taken from the owner +// Asset assetSold; +// int64 amountSold; +// +// // amount and asset sent to the owner +// Asset assetBought; +// int64 amountBought; +// }; + +// =========================================================================== +public class ClaimOfferAtom { + public ClaimOfferAtom () {} + private AccountID sellerID; + public AccountID getSellerID() { + return this.sellerID; + } + public void setSellerID(AccountID value) { + this.sellerID = value; + } + private Uint64 offerID; + public Uint64 getOfferID() { + return this.offerID; + } + public void setOfferID(Uint64 value) { + this.offerID = value; + } + private Asset assetSold; + public Asset getAssetSold() { + return this.assetSold; + } + public void setAssetSold(Asset value) { + this.assetSold = value; + } + private Int64 amountSold; + public Int64 getAmountSold() { + return this.amountSold; + } + public void setAmountSold(Int64 value) { + this.amountSold = value; + } + private Asset assetBought; + public Asset getAssetBought() { + return this.assetBought; + } + public void setAssetBought(Asset value) { + this.assetBought = value; + } + private Int64 amountBought; + public Int64 getAmountBought() { + return this.amountBought; + } + public void setAmountBought(Int64 value) { + this.amountBought = value; + } + public static void encode(XdrDataOutputStream stream, ClaimOfferAtom encodedClaimOfferAtom) throws IOException{ + AccountID.encode(stream, encodedClaimOfferAtom.sellerID); + Uint64.encode(stream, encodedClaimOfferAtom.offerID); + Asset.encode(stream, encodedClaimOfferAtom.assetSold); + Int64.encode(stream, encodedClaimOfferAtom.amountSold); + Asset.encode(stream, encodedClaimOfferAtom.assetBought); + Int64.encode(stream, encodedClaimOfferAtom.amountBought); + } + public static ClaimOfferAtom decode(XdrDataInputStream stream) throws IOException { + ClaimOfferAtom decodedClaimOfferAtom = new ClaimOfferAtom(); + decodedClaimOfferAtom.sellerID = AccountID.decode(stream); + decodedClaimOfferAtom.offerID = Uint64.decode(stream); + decodedClaimOfferAtom.assetSold = Asset.decode(stream); + decodedClaimOfferAtom.amountSold = Int64.decode(stream); + decodedClaimOfferAtom.assetBought = Asset.decode(stream); + decodedClaimOfferAtom.amountBought = Int64.decode(stream); + return decodedClaimOfferAtom; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/CreateAccountOp.java b/app/src/main/java/org/stellar/sdk/xdr/CreateAccountOp.java new file mode 100644 index 0000000000..def2fd2386 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/CreateAccountOp.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct CreateAccountOp +// { +// AccountID destination; // account to create +// int64 startingBalance; // amount they end up with +// }; + +// =========================================================================== +public class CreateAccountOp { + public CreateAccountOp () {} + private AccountID destination; + public AccountID getDestination() { + return this.destination; + } + public void setDestination(AccountID value) { + this.destination = value; + } + private Int64 startingBalance; + public Int64 getStartingBalance() { + return this.startingBalance; + } + public void setStartingBalance(Int64 value) { + this.startingBalance = value; + } + public static void encode(XdrDataOutputStream stream, CreateAccountOp encodedCreateAccountOp) throws IOException{ + AccountID.encode(stream, encodedCreateAccountOp.destination); + Int64.encode(stream, encodedCreateAccountOp.startingBalance); + } + public static CreateAccountOp decode(XdrDataInputStream stream) throws IOException { + CreateAccountOp decodedCreateAccountOp = new CreateAccountOp(); + decodedCreateAccountOp.destination = AccountID.decode(stream); + decodedCreateAccountOp.startingBalance = Int64.decode(stream); + return decodedCreateAccountOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/CreateAccountResult.java b/app/src/main/java/org/stellar/sdk/xdr/CreateAccountResult.java new file mode 100644 index 0000000000..34ce78cb2b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/CreateAccountResult.java @@ -0,0 +1,50 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union CreateAccountResult switch (CreateAccountResultCode code) +// { +// case CREATE_ACCOUNT_SUCCESS: +// void; +// default: +// void; +// }; + +// =========================================================================== +public class CreateAccountResult { + public CreateAccountResult () {} + CreateAccountResultCode code; + public CreateAccountResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(CreateAccountResultCode value) { + this.code = value; + } + public static void encode(XdrDataOutputStream stream, CreateAccountResult encodedCreateAccountResult) throws IOException { + stream.writeInt(encodedCreateAccountResult.getDiscriminant().getValue()); + switch (encodedCreateAccountResult.getDiscriminant()) { + case CREATE_ACCOUNT_SUCCESS: + break; + default: + break; + } + } + public static CreateAccountResult decode(XdrDataInputStream stream) throws IOException { + CreateAccountResult decodedCreateAccountResult = new CreateAccountResult(); + CreateAccountResultCode discriminant = CreateAccountResultCode.decode(stream); + decodedCreateAccountResult.setDiscriminant(discriminant); + switch (decodedCreateAccountResult.getDiscriminant()) { + case CREATE_ACCOUNT_SUCCESS: + break; + default: + break; + } + return decodedCreateAccountResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/CreateAccountResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/CreateAccountResultCode.java new file mode 100644 index 0000000000..8218c20bb8 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/CreateAccountResultCode.java @@ -0,0 +1,58 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum CreateAccountResultCode +// { +// // codes considered as "success" for the operation +// CREATE_ACCOUNT_SUCCESS = 0, // account was created +// +// // codes considered as "failure" for the operation +// CREATE_ACCOUNT_MALFORMED = -1, // invalid destination +// CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account +// CREATE_ACCOUNT_LOW_RESERVE = +// -3, // would create an account below the min reserve +// CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists +// }; + +// =========================================================================== +public enum CreateAccountResultCode { + CREATE_ACCOUNT_SUCCESS(0), + CREATE_ACCOUNT_MALFORMED(-1), + CREATE_ACCOUNT_UNDERFUNDED(-2), + CREATE_ACCOUNT_LOW_RESERVE(-3), + CREATE_ACCOUNT_ALREADY_EXIST(-4), + ; + private int mValue; + + CreateAccountResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static CreateAccountResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return CREATE_ACCOUNT_SUCCESS; + case -1: return CREATE_ACCOUNT_MALFORMED; + case -2: return CREATE_ACCOUNT_UNDERFUNDED; + case -3: return CREATE_ACCOUNT_LOW_RESERVE; + case -4: return CREATE_ACCOUNT_ALREADY_EXIST; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, CreateAccountResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/CreatePassiveOfferOp.java b/app/src/main/java/org/stellar/sdk/xdr/CreatePassiveOfferOp.java new file mode 100644 index 0000000000..2deddc4350 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/CreatePassiveOfferOp.java @@ -0,0 +1,64 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct CreatePassiveOfferOp +// { +// Asset selling; // A +// Asset buying; // B +// int64 amount; // amount taker gets. if set to 0, delete the offer +// Price price; // cost of A in terms of B +// }; + +// =========================================================================== +public class CreatePassiveOfferOp { + public CreatePassiveOfferOp () {} + private Asset selling; + public Asset getSelling() { + return this.selling; + } + public void setSelling(Asset value) { + this.selling = value; + } + private Asset buying; + public Asset getBuying() { + return this.buying; + } + public void setBuying(Asset value) { + this.buying = value; + } + private Int64 amount; + public Int64 getAmount() { + return this.amount; + } + public void setAmount(Int64 value) { + this.amount = value; + } + private Price price; + public Price getPrice() { + return this.price; + } + public void setPrice(Price value) { + this.price = value; + } + public static void encode(XdrDataOutputStream stream, CreatePassiveOfferOp encodedCreatePassiveOfferOp) throws IOException{ + Asset.encode(stream, encodedCreatePassiveOfferOp.selling); + Asset.encode(stream, encodedCreatePassiveOfferOp.buying); + Int64.encode(stream, encodedCreatePassiveOfferOp.amount); + Price.encode(stream, encodedCreatePassiveOfferOp.price); + } + public static CreatePassiveOfferOp decode(XdrDataInputStream stream) throws IOException { + CreatePassiveOfferOp decodedCreatePassiveOfferOp = new CreatePassiveOfferOp(); + decodedCreatePassiveOfferOp.selling = Asset.decode(stream); + decodedCreatePassiveOfferOp.buying = Asset.decode(stream); + decodedCreatePassiveOfferOp.amount = Int64.decode(stream); + decodedCreatePassiveOfferOp.price = Price.decode(stream); + return decodedCreatePassiveOfferOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/CryptoKeyType.java b/app/src/main/java/org/stellar/sdk/xdr/CryptoKeyType.java new file mode 100644 index 0000000000..5f710b4a24 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/CryptoKeyType.java @@ -0,0 +1,48 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum CryptoKeyType +// { +// KEY_TYPE_ED25519 = 0, +// KEY_TYPE_PRE_AUTH_TX = 1, +// KEY_TYPE_HASH_X = 2 +// }; + +// =========================================================================== +public enum CryptoKeyType { + KEY_TYPE_ED25519(0), + KEY_TYPE_PRE_AUTH_TX(1), + KEY_TYPE_HASH_X(2), + ; + private int mValue; + + CryptoKeyType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static CryptoKeyType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return KEY_TYPE_ED25519; + case 1: return KEY_TYPE_PRE_AUTH_TX; + case 2: return KEY_TYPE_HASH_X; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, CryptoKeyType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Curve25519Public.java b/app/src/main/java/org/stellar/sdk/xdr/Curve25519Public.java new file mode 100644 index 0000000000..e2a65a0621 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Curve25519Public.java @@ -0,0 +1,37 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Curve25519Public +// { +// opaque key[32]; +// }; + +// =========================================================================== +public class Curve25519Public { + public Curve25519Public () {} + private byte[] key; + public byte[] getKey() { + return this.key; + } + public void setKey(byte[] value) { + this.key = value; + } + public static void encode(XdrDataOutputStream stream, Curve25519Public encodedCurve25519Public) throws IOException{ + int keysize = encodedCurve25519Public.key.length; + stream.write(encodedCurve25519Public.getKey(), 0, keysize); + } + public static Curve25519Public decode(XdrDataInputStream stream) throws IOException { + Curve25519Public decodedCurve25519Public = new Curve25519Public(); + int keysize = 32; + decodedCurve25519Public.key = new byte[keysize]; + stream.read(decodedCurve25519Public.key, 0, keysize); + return decodedCurve25519Public; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Curve25519Secret.java b/app/src/main/java/org/stellar/sdk/xdr/Curve25519Secret.java new file mode 100644 index 0000000000..2ba03a9c51 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Curve25519Secret.java @@ -0,0 +1,37 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Curve25519Secret +// { +// opaque key[32]; +// }; + +// =========================================================================== +public class Curve25519Secret { + public Curve25519Secret () {} + private byte[] key; + public byte[] getKey() { + return this.key; + } + public void setKey(byte[] value) { + this.key = value; + } + public static void encode(XdrDataOutputStream stream, Curve25519Secret encodedCurve25519Secret) throws IOException{ + int keysize = encodedCurve25519Secret.key.length; + stream.write(encodedCurve25519Secret.getKey(), 0, keysize); + } + public static Curve25519Secret decode(XdrDataInputStream stream) throws IOException { + Curve25519Secret decodedCurve25519Secret = new Curve25519Secret(); + int keysize = 32; + decodedCurve25519Secret.key = new byte[keysize]; + stream.read(decodedCurve25519Secret.key, 0, keysize); + return decodedCurve25519Secret; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/DataEntry.java b/app/src/main/java/org/stellar/sdk/xdr/DataEntry.java new file mode 100644 index 0000000000..013d067dd5 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/DataEntry.java @@ -0,0 +1,100 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct DataEntry +// { +// AccountID accountID; // account this data belongs to +// string64 dataName; +// DataValue dataValue; +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class DataEntry { + public DataEntry () {} + private AccountID accountID; + public AccountID getAccountID() { + return this.accountID; + } + public void setAccountID(AccountID value) { + this.accountID = value; + } + private String64 dataName; + public String64 getDataName() { + return this.dataName; + } + public void setDataName(String64 value) { + this.dataName = value; + } + private DataValue dataValue; + public DataValue getDataValue() { + return this.dataValue; + } + public void setDataValue(DataValue value) { + this.dataValue = value; + } + private DataEntryExt ext; + public DataEntryExt getExt() { + return this.ext; + } + public void setExt(DataEntryExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, DataEntry encodedDataEntry) throws IOException{ + AccountID.encode(stream, encodedDataEntry.accountID); + String64.encode(stream, encodedDataEntry.dataName); + DataValue.encode(stream, encodedDataEntry.dataValue); + DataEntryExt.encode(stream, encodedDataEntry.ext); + } + public static DataEntry decode(XdrDataInputStream stream) throws IOException { + DataEntry decodedDataEntry = new DataEntry(); + decodedDataEntry.accountID = AccountID.decode(stream); + decodedDataEntry.dataName = String64.decode(stream); + decodedDataEntry.dataValue = DataValue.decode(stream); + decodedDataEntry.ext = DataEntryExt.decode(stream); + return decodedDataEntry; + } + + public static class DataEntryExt { + public DataEntryExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, DataEntryExt encodedDataEntryExt) throws IOException { + stream.writeInt(encodedDataEntryExt.getDiscriminant().intValue()); + switch (encodedDataEntryExt.getDiscriminant()) { + case 0: + break; + } + } + public static DataEntryExt decode(XdrDataInputStream stream) throws IOException { + DataEntryExt decodedDataEntryExt = new DataEntryExt(); + Integer discriminant = stream.readInt(); + decodedDataEntryExt.setDiscriminant(discriminant); + switch (decodedDataEntryExt.getDiscriminant()) { + case 0: + break; + } + return decodedDataEntryExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/DataValue.java b/app/src/main/java/org/stellar/sdk/xdr/DataValue.java new file mode 100644 index 0000000000..12743dc129 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/DataValue.java @@ -0,0 +1,34 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef opaque DataValue<64>; + +// =========================================================================== +public class DataValue { + private byte[] DataValue; + public byte[] getDataValue() { + return this.DataValue; + } + public void setDataValue(byte[] value) { + this.DataValue = value; + } + public static void encode(XdrDataOutputStream stream, DataValue encodedDataValue) throws IOException { + int DataValuesize = encodedDataValue.DataValue.length; + stream.writeInt(DataValuesize); + stream.write(encodedDataValue.getDataValue(), 0, DataValuesize); + } + public static DataValue decode(XdrDataInputStream stream) throws IOException { + DataValue decodedDataValue = new DataValue(); + int DataValuesize = stream.readInt(); + decodedDataValue.DataValue = new byte[DataValuesize]; + stream.read(decodedDataValue.DataValue, 0, DataValuesize); + return decodedDataValue; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/DecoratedSignature.java b/app/src/main/java/org/stellar/sdk/xdr/DecoratedSignature.java new file mode 100644 index 0000000000..27b622b719 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/DecoratedSignature.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct DecoratedSignature +// { +// SignatureHint hint; // last 4 bytes of the public key, used as a hint +// Signature signature; // actual signature +// }; + +// =========================================================================== +public class DecoratedSignature { + public DecoratedSignature () {} + private SignatureHint hint; + public SignatureHint getHint() { + return this.hint; + } + public void setHint(SignatureHint value) { + this.hint = value; + } + private Signature signature; + public Signature getSignature() { + return this.signature; + } + public void setSignature(Signature value) { + this.signature = value; + } + public static void encode(XdrDataOutputStream stream, DecoratedSignature encodedDecoratedSignature) throws IOException{ + SignatureHint.encode(stream, encodedDecoratedSignature.hint); + Signature.encode(stream, encodedDecoratedSignature.signature); + } + public static DecoratedSignature decode(XdrDataInputStream stream) throws IOException { + DecoratedSignature decodedDecoratedSignature = new DecoratedSignature(); + decodedDecoratedSignature.hint = SignatureHint.decode(stream); + decodedDecoratedSignature.signature = Signature.decode(stream); + return decodedDecoratedSignature; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/DontHave.java b/app/src/main/java/org/stellar/sdk/xdr/DontHave.java new file mode 100644 index 0000000000..9b3b711af1 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/DontHave.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct DontHave +// { +// MessageType type; +// uint256 reqHash; +// }; + +// =========================================================================== +public class DontHave { + public DontHave () {} + private MessageType type; + public MessageType getType() { + return this.type; + } + public void setType(MessageType value) { + this.type = value; + } + private Uint256 reqHash; + public Uint256 getReqHash() { + return this.reqHash; + } + public void setReqHash(Uint256 value) { + this.reqHash = value; + } + public static void encode(XdrDataOutputStream stream, DontHave encodedDontHave) throws IOException{ + MessageType.encode(stream, encodedDontHave.type); + Uint256.encode(stream, encodedDontHave.reqHash); + } + public static DontHave decode(XdrDataInputStream stream) throws IOException { + DontHave decodedDontHave = new DontHave(); + decodedDontHave.type = MessageType.decode(stream); + decodedDontHave.reqHash = Uint256.decode(stream); + return decodedDontHave; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/EnvelopeType.java b/app/src/main/java/org/stellar/sdk/xdr/EnvelopeType.java new file mode 100644 index 0000000000..2b6a9c73b9 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/EnvelopeType.java @@ -0,0 +1,48 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum EnvelopeType +// { +// ENVELOPE_TYPE_SCP = 1, +// ENVELOPE_TYPE_TX = 2, +// ENVELOPE_TYPE_AUTH = 3 +// }; + +// =========================================================================== +public enum EnvelopeType { + ENVELOPE_TYPE_SCP(1), + ENVELOPE_TYPE_TX(2), + ENVELOPE_TYPE_AUTH(3), + ; + private int mValue; + + EnvelopeType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static EnvelopeType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 1: return ENVELOPE_TYPE_SCP; + case 2: return ENVELOPE_TYPE_TX; + case 3: return ENVELOPE_TYPE_AUTH; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, EnvelopeType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Error.java b/app/src/main/java/org/stellar/sdk/xdr/Error.java new file mode 100644 index 0000000000..7e8df3bb9f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Error.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Error +// { +// ErrorCode code; +// string msg<100>; +// }; + +// =========================================================================== +public class Error { + public Error () {} + private ErrorCode code; + public ErrorCode getCode() { + return this.code; + } + public void setCode(ErrorCode value) { + this.code = value; + } + private String msg; + public String getMsg() { + return this.msg; + } + public void setMsg(String value) { + this.msg = value; + } + public static void encode(XdrDataOutputStream stream, Error encodedError) throws IOException{ + ErrorCode.encode(stream, encodedError.code); + stream.writeString(encodedError.msg); + } + public static Error decode(XdrDataInputStream stream) throws IOException { + Error decodedError = new Error(); + decodedError.code = ErrorCode.decode(stream); + decodedError.msg = stream.readString(); + return decodedError; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ErrorCode.java b/app/src/main/java/org/stellar/sdk/xdr/ErrorCode.java new file mode 100644 index 0000000000..ec3ad623c2 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ErrorCode.java @@ -0,0 +1,54 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum ErrorCode +// { +// ERR_MISC = 0, // Unspecific error +// ERR_DATA = 1, // Malformed data +// ERR_CONF = 2, // Misconfiguration error +// ERR_AUTH = 3, // Authentication failure +// ERR_LOAD = 4 // System overloaded +// }; + +// =========================================================================== +public enum ErrorCode { + ERR_MISC(0), + ERR_DATA(1), + ERR_CONF(2), + ERR_AUTH(3), + ERR_LOAD(4), + ; + private int mValue; + + ErrorCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static ErrorCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return ERR_MISC; + case 1: return ERR_DATA; + case 2: return ERR_CONF; + case 3: return ERR_AUTH; + case 4: return ERR_LOAD; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, ErrorCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Hash.java b/app/src/main/java/org/stellar/sdk/xdr/Hash.java new file mode 100644 index 0000000000..f8adea9877 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Hash.java @@ -0,0 +1,33 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef opaque Hash[32]; + +// =========================================================================== +public class Hash { + private byte[] Hash; + public byte[] getHash() { + return this.Hash; + } + public void setHash(byte[] value) { + this.Hash = value; + } + public static void encode(XdrDataOutputStream stream, Hash encodedHash) throws IOException { + int Hashsize = encodedHash.Hash.length; + stream.write(encodedHash.getHash(), 0, Hashsize); + } + public static Hash decode(XdrDataInputStream stream) throws IOException { + Hash decodedHash = new Hash(); + int Hashsize = 32; + decodedHash.Hash = new byte[Hashsize]; + stream.read(decodedHash.Hash, 0, Hashsize); + return decodedHash; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Hello.java b/app/src/main/java/org/stellar/sdk/xdr/Hello.java new file mode 100644 index 0000000000..cbb6faa07d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Hello.java @@ -0,0 +1,114 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Hello +// { +// uint32 ledgerVersion; +// uint32 overlayVersion; +// uint32 overlayMinVersion; +// Hash networkID; +// string versionStr<100>; +// int listeningPort; +// NodeID peerID; +// AuthCert cert; +// uint256 nonce; +// }; + +// =========================================================================== +public class Hello { + public Hello () {} + private Uint32 ledgerVersion; + public Uint32 getLedgerVersion() { + return this.ledgerVersion; + } + public void setLedgerVersion(Uint32 value) { + this.ledgerVersion = value; + } + private Uint32 overlayVersion; + public Uint32 getOverlayVersion() { + return this.overlayVersion; + } + public void setOverlayVersion(Uint32 value) { + this.overlayVersion = value; + } + private Uint32 overlayMinVersion; + public Uint32 getOverlayMinVersion() { + return this.overlayMinVersion; + } + public void setOverlayMinVersion(Uint32 value) { + this.overlayMinVersion = value; + } + private Hash networkID; + public Hash getNetworkID() { + return this.networkID; + } + public void setNetworkID(Hash value) { + this.networkID = value; + } + private String versionStr; + public String getVersionStr() { + return this.versionStr; + } + public void setVersionStr(String value) { + this.versionStr = value; + } + private Integer listeningPort; + public Integer getListeningPort() { + return this.listeningPort; + } + public void setListeningPort(Integer value) { + this.listeningPort = value; + } + private NodeID peerID; + public NodeID getPeerID() { + return this.peerID; + } + public void setPeerID(NodeID value) { + this.peerID = value; + } + private AuthCert cert; + public AuthCert getCert() { + return this.cert; + } + public void setCert(AuthCert value) { + this.cert = value; + } + private Uint256 nonce; + public Uint256 getNonce() { + return this.nonce; + } + public void setNonce(Uint256 value) { + this.nonce = value; + } + public static void encode(XdrDataOutputStream stream, Hello encodedHello) throws IOException{ + Uint32.encode(stream, encodedHello.ledgerVersion); + Uint32.encode(stream, encodedHello.overlayVersion); + Uint32.encode(stream, encodedHello.overlayMinVersion); + Hash.encode(stream, encodedHello.networkID); + stream.writeString(encodedHello.versionStr); + stream.writeInt(encodedHello.listeningPort); + NodeID.encode(stream, encodedHello.peerID); + AuthCert.encode(stream, encodedHello.cert); + Uint256.encode(stream, encodedHello.nonce); + } + public static Hello decode(XdrDataInputStream stream) throws IOException { + Hello decodedHello = new Hello(); + decodedHello.ledgerVersion = Uint32.decode(stream); + decodedHello.overlayVersion = Uint32.decode(stream); + decodedHello.overlayMinVersion = Uint32.decode(stream); + decodedHello.networkID = Hash.decode(stream); + decodedHello.versionStr = stream.readString(); + decodedHello.listeningPort = stream.readInt(); + decodedHello.peerID = NodeID.decode(stream); + decodedHello.cert = AuthCert.decode(stream); + decodedHello.nonce = Uint256.decode(stream); + return decodedHello; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/HmacSha256Key.java b/app/src/main/java/org/stellar/sdk/xdr/HmacSha256Key.java new file mode 100644 index 0000000000..e17c74a35d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/HmacSha256Key.java @@ -0,0 +1,37 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct HmacSha256Key +// { +// opaque key[32]; +// }; + +// =========================================================================== +public class HmacSha256Key { + public HmacSha256Key () {} + private byte[] key; + public byte[] getKey() { + return this.key; + } + public void setKey(byte[] value) { + this.key = value; + } + public static void encode(XdrDataOutputStream stream, HmacSha256Key encodedHmacSha256Key) throws IOException{ + int keysize = encodedHmacSha256Key.key.length; + stream.write(encodedHmacSha256Key.getKey(), 0, keysize); + } + public static HmacSha256Key decode(XdrDataInputStream stream) throws IOException { + HmacSha256Key decodedHmacSha256Key = new HmacSha256Key(); + int keysize = 32; + decodedHmacSha256Key.key = new byte[keysize]; + stream.read(decodedHmacSha256Key.key, 0, keysize); + return decodedHmacSha256Key; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/HmacSha256Mac.java b/app/src/main/java/org/stellar/sdk/xdr/HmacSha256Mac.java new file mode 100644 index 0000000000..cbfb8b2c21 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/HmacSha256Mac.java @@ -0,0 +1,37 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct HmacSha256Mac +// { +// opaque mac[32]; +// }; + +// =========================================================================== +public class HmacSha256Mac { + public HmacSha256Mac () {} + private byte[] mac; + public byte[] getMac() { + return this.mac; + } + public void setMac(byte[] value) { + this.mac = value; + } + public static void encode(XdrDataOutputStream stream, HmacSha256Mac encodedHmacSha256Mac) throws IOException{ + int macsize = encodedHmacSha256Mac.mac.length; + stream.write(encodedHmacSha256Mac.getMac(), 0, macsize); + } + public static HmacSha256Mac decode(XdrDataInputStream stream) throws IOException { + HmacSha256Mac decodedHmacSha256Mac = new HmacSha256Mac(); + int macsize = 32; + decodedHmacSha256Mac.mac = new byte[macsize]; + stream.read(decodedHmacSha256Mac.mac, 0, macsize); + return decodedHmacSha256Mac; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/IPAddrType.java b/app/src/main/java/org/stellar/sdk/xdr/IPAddrType.java new file mode 100644 index 0000000000..edfbbe1b31 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/IPAddrType.java @@ -0,0 +1,45 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum IPAddrType +// { +// IPv4 = 0, +// IPv6 = 1 +// }; + +// =========================================================================== +public enum IPAddrType { + IPv4(0), + IPv6(1), + ; + private int mValue; + + IPAddrType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static IPAddrType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return IPv4; + case 1: return IPv6; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, IPAddrType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/InflationPayout.java b/app/src/main/java/org/stellar/sdk/xdr/InflationPayout.java new file mode 100644 index 0000000000..5484ae28d6 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/InflationPayout.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct InflationPayout // or use PaymentResultAtom to limit types? +// { +// AccountID destination; +// int64 amount; +// }; + +// =========================================================================== +public class InflationPayout { + public InflationPayout () {} + private AccountID destination; + public AccountID getDestination() { + return this.destination; + } + public void setDestination(AccountID value) { + this.destination = value; + } + private Int64 amount; + public Int64 getAmount() { + return this.amount; + } + public void setAmount(Int64 value) { + this.amount = value; + } + public static void encode(XdrDataOutputStream stream, InflationPayout encodedInflationPayout) throws IOException{ + AccountID.encode(stream, encodedInflationPayout.destination); + Int64.encode(stream, encodedInflationPayout.amount); + } + public static InflationPayout decode(XdrDataInputStream stream) throws IOException { + InflationPayout decodedInflationPayout = new InflationPayout(); + decodedInflationPayout.destination = AccountID.decode(stream); + decodedInflationPayout.amount = Int64.decode(stream); + return decodedInflationPayout; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/InflationResult.java b/app/src/main/java/org/stellar/sdk/xdr/InflationResult.java new file mode 100644 index 0000000000..d82e798923 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/InflationResult.java @@ -0,0 +1,67 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union InflationResult switch (InflationResultCode code) +// { +// case INFLATION_SUCCESS: +// InflationPayout payouts<>; +// default: +// void; +// }; + +// =========================================================================== +public class InflationResult { + public InflationResult () {} + InflationResultCode code; + public InflationResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(InflationResultCode value) { + this.code = value; + } + private InflationPayout[] payouts; + public InflationPayout[] getPayouts() { + return this.payouts; + } + public void setPayouts(InflationPayout[] value) { + this.payouts = value; + } + public static void encode(XdrDataOutputStream stream, InflationResult encodedInflationResult) throws IOException { + stream.writeInt(encodedInflationResult.getDiscriminant().getValue()); + switch (encodedInflationResult.getDiscriminant()) { + case INFLATION_SUCCESS: + int payoutssize = encodedInflationResult.getPayouts().length; + stream.writeInt(payoutssize); + for (int i = 0; i < payoutssize; i++) { + InflationPayout.encode(stream, encodedInflationResult.payouts[i]); + } + break; + default: + break; + } + } + public static InflationResult decode(XdrDataInputStream stream) throws IOException { + InflationResult decodedInflationResult = new InflationResult(); + InflationResultCode discriminant = InflationResultCode.decode(stream); + decodedInflationResult.setDiscriminant(discriminant); + switch (decodedInflationResult.getDiscriminant()) { + case INFLATION_SUCCESS: + int payoutssize = stream.readInt(); + decodedInflationResult.payouts = new InflationPayout[payoutssize]; + for (int i = 0; i < payoutssize; i++) { + decodedInflationResult.payouts[i] = InflationPayout.decode(stream); + } + break; + default: + break; + } + return decodedInflationResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/InflationResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/InflationResultCode.java new file mode 100644 index 0000000000..d146a9978d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/InflationResultCode.java @@ -0,0 +1,47 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum InflationResultCode +// { +// // codes considered as "success" for the operation +// INFLATION_SUCCESS = 0, +// // codes considered as "failure" for the operation +// INFLATION_NOT_TIME = -1 +// }; + +// =========================================================================== +public enum InflationResultCode { + INFLATION_SUCCESS(0), + INFLATION_NOT_TIME(-1), + ; + private int mValue; + + InflationResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static InflationResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return INFLATION_SUCCESS; + case -1: return INFLATION_NOT_TIME; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, InflationResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Int32.java b/app/src/main/java/org/stellar/sdk/xdr/Int32.java new file mode 100644 index 0000000000..be9ea4820b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Int32.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef int int32; + +// =========================================================================== +public class Int32 { + private Integer int32; + public Integer getInt32() { + return this.int32; + } + public void setInt32(Integer value) { + this.int32 = value; + } + public static void encode(XdrDataOutputStream stream, Int32 encodedInt32) throws IOException { + stream.writeInt(encodedInt32.int32); + } + public static Int32 decode(XdrDataInputStream stream) throws IOException { + Int32 decodedInt32 = new Int32(); + decodedInt32.int32 = stream.readInt(); + return decodedInt32; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Int64.java b/app/src/main/java/org/stellar/sdk/xdr/Int64.java new file mode 100644 index 0000000000..88d0b7ce4b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Int64.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef hyper int64; + +// =========================================================================== +public class Int64 { + private Long int64; + public Long getInt64() { + return this.int64; + } + public void setInt64(Long value) { + this.int64 = value; + } + public static void encode(XdrDataOutputStream stream, Int64 encodedInt64) throws IOException { + stream.writeLong(encodedInt64.int64); + } + public static Int64 decode(XdrDataInputStream stream) throws IOException { + Int64 decodedInt64 = new Int64(); + decodedInt64.int64 = stream.readLong(); + return decodedInt64; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerEntry.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntry.java new file mode 100644 index 0000000000..7c8f73e5c7 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntry.java @@ -0,0 +1,178 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct LedgerEntry +// { +// uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed +// +// union switch (LedgerEntryType type) +// { +// case ACCOUNT: +// AccountEntry account; +// case TRUSTLINE: +// TrustLineEntry trustLine; +// case OFFER: +// OfferEntry offer; +// case DATA: +// DataEntry data; +// } +// data; +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class LedgerEntry { + public LedgerEntry () {} + private Uint32 lastModifiedLedgerSeq; + public Uint32 getLastModifiedLedgerSeq() { + return this.lastModifiedLedgerSeq; + } + public void setLastModifiedLedgerSeq(Uint32 value) { + this.lastModifiedLedgerSeq = value; + } + private LedgerEntryData data; + public LedgerEntryData getData() { + return this.data; + } + public void setData(LedgerEntryData value) { + this.data = value; + } + private LedgerEntryExt ext; + public LedgerEntryExt getExt() { + return this.ext; + } + public void setExt(LedgerEntryExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, LedgerEntry encodedLedgerEntry) throws IOException{ + Uint32.encode(stream, encodedLedgerEntry.lastModifiedLedgerSeq); + LedgerEntryData.encode(stream, encodedLedgerEntry.data); + LedgerEntryExt.encode(stream, encodedLedgerEntry.ext); + } + public static LedgerEntry decode(XdrDataInputStream stream) throws IOException { + LedgerEntry decodedLedgerEntry = new LedgerEntry(); + decodedLedgerEntry.lastModifiedLedgerSeq = Uint32.decode(stream); + decodedLedgerEntry.data = LedgerEntryData.decode(stream); + decodedLedgerEntry.ext = LedgerEntryExt.decode(stream); + return decodedLedgerEntry; + } + + public static class LedgerEntryData { + public LedgerEntryData () {} + LedgerEntryType type; + public LedgerEntryType getDiscriminant() { + return this.type; + } + public void setDiscriminant(LedgerEntryType value) { + this.type = value; + } + private AccountEntry account; + public AccountEntry getAccount() { + return this.account; + } + public void setAccount(AccountEntry value) { + this.account = value; + } + private TrustLineEntry trustLine; + public TrustLineEntry getTrustLine() { + return this.trustLine; + } + public void setTrustLine(TrustLineEntry value) { + this.trustLine = value; + } + private OfferEntry offer; + public OfferEntry getOffer() { + return this.offer; + } + public void setOffer(OfferEntry value) { + this.offer = value; + } + private DataEntry data; + public DataEntry getData() { + return this.data; + } + public void setData(DataEntry value) { + this.data = value; + } + public static void encode(XdrDataOutputStream stream, LedgerEntryData encodedLedgerEntryData) throws IOException { + stream.writeInt(encodedLedgerEntryData.getDiscriminant().getValue()); + switch (encodedLedgerEntryData.getDiscriminant()) { + case ACCOUNT: + AccountEntry.encode(stream, encodedLedgerEntryData.account); + break; + case TRUSTLINE: + TrustLineEntry.encode(stream, encodedLedgerEntryData.trustLine); + break; + case OFFER: + OfferEntry.encode(stream, encodedLedgerEntryData.offer); + break; + case DATA: + DataEntry.encode(stream, encodedLedgerEntryData.data); + break; + } + } + public static LedgerEntryData decode(XdrDataInputStream stream) throws IOException { + LedgerEntryData decodedLedgerEntryData = new LedgerEntryData(); + LedgerEntryType discriminant = LedgerEntryType.decode(stream); + decodedLedgerEntryData.setDiscriminant(discriminant); + switch (decodedLedgerEntryData.getDiscriminant()) { + case ACCOUNT: + decodedLedgerEntryData.account = AccountEntry.decode(stream); + break; + case TRUSTLINE: + decodedLedgerEntryData.trustLine = TrustLineEntry.decode(stream); + break; + case OFFER: + decodedLedgerEntryData.offer = OfferEntry.decode(stream); + break; + case DATA: + decodedLedgerEntryData.data = DataEntry.decode(stream); + break; + } + return decodedLedgerEntryData; + } + + } + public static class LedgerEntryExt { + public LedgerEntryExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, LedgerEntryExt encodedLedgerEntryExt) throws IOException { + stream.writeInt(encodedLedgerEntryExt.getDiscriminant().intValue()); + switch (encodedLedgerEntryExt.getDiscriminant()) { + case 0: + break; + } + } + public static LedgerEntryExt decode(XdrDataInputStream stream) throws IOException { + LedgerEntryExt decodedLedgerEntryExt = new LedgerEntryExt(); + Integer discriminant = stream.readInt(); + decodedLedgerEntryExt.setDiscriminant(discriminant); + switch (decodedLedgerEntryExt.getDiscriminant()) { + case 0: + break; + } + return decodedLedgerEntryExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChange.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChange.java new file mode 100644 index 0000000000..9837c4b53b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChange.java @@ -0,0 +1,98 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union LedgerEntryChange switch (LedgerEntryChangeType type) +// { +// case LEDGER_ENTRY_CREATED: +// LedgerEntry created; +// case LEDGER_ENTRY_UPDATED: +// LedgerEntry updated; +// case LEDGER_ENTRY_REMOVED: +// LedgerKey removed; +// case LEDGER_ENTRY_STATE: +// LedgerEntry state; +// }; + +// =========================================================================== +public class LedgerEntryChange { + public LedgerEntryChange () {} + LedgerEntryChangeType type; + public LedgerEntryChangeType getDiscriminant() { + return this.type; + } + public void setDiscriminant(LedgerEntryChangeType value) { + this.type = value; + } + private LedgerEntry created; + public LedgerEntry getCreated() { + return this.created; + } + public void setCreated(LedgerEntry value) { + this.created = value; + } + private LedgerEntry updated; + public LedgerEntry getUpdated() { + return this.updated; + } + public void setUpdated(LedgerEntry value) { + this.updated = value; + } + private LedgerKey removed; + public LedgerKey getRemoved() { + return this.removed; + } + public void setRemoved(LedgerKey value) { + this.removed = value; + } + private LedgerEntry state; + public LedgerEntry getState() { + return this.state; + } + public void setState(LedgerEntry value) { + this.state = value; + } + public static void encode(XdrDataOutputStream stream, LedgerEntryChange encodedLedgerEntryChange) throws IOException { + stream.writeInt(encodedLedgerEntryChange.getDiscriminant().getValue()); + switch (encodedLedgerEntryChange.getDiscriminant()) { + case LEDGER_ENTRY_CREATED: + LedgerEntry.encode(stream, encodedLedgerEntryChange.created); + break; + case LEDGER_ENTRY_UPDATED: + LedgerEntry.encode(stream, encodedLedgerEntryChange.updated); + break; + case LEDGER_ENTRY_REMOVED: + LedgerKey.encode(stream, encodedLedgerEntryChange.removed); + break; + case LEDGER_ENTRY_STATE: + LedgerEntry.encode(stream, encodedLedgerEntryChange.state); + break; + } + } + public static LedgerEntryChange decode(XdrDataInputStream stream) throws IOException { + LedgerEntryChange decodedLedgerEntryChange = new LedgerEntryChange(); + LedgerEntryChangeType discriminant = LedgerEntryChangeType.decode(stream); + decodedLedgerEntryChange.setDiscriminant(discriminant); + switch (decodedLedgerEntryChange.getDiscriminant()) { + case LEDGER_ENTRY_CREATED: + decodedLedgerEntryChange.created = LedgerEntry.decode(stream); + break; + case LEDGER_ENTRY_UPDATED: + decodedLedgerEntryChange.updated = LedgerEntry.decode(stream); + break; + case LEDGER_ENTRY_REMOVED: + decodedLedgerEntryChange.removed = LedgerKey.decode(stream); + break; + case LEDGER_ENTRY_STATE: + decodedLedgerEntryChange.state = LedgerEntry.decode(stream); + break; + } + return decodedLedgerEntryChange; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChangeType.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChangeType.java new file mode 100644 index 0000000000..6ebdd01614 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChangeType.java @@ -0,0 +1,51 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum LedgerEntryChangeType +// { +// LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger +// LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger +// LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger +// LEDGER_ENTRY_STATE = 3 // value of the entry +// }; + +// =========================================================================== +public enum LedgerEntryChangeType { + LEDGER_ENTRY_CREATED(0), + LEDGER_ENTRY_UPDATED(1), + LEDGER_ENTRY_REMOVED(2), + LEDGER_ENTRY_STATE(3), + ; + private int mValue; + + LedgerEntryChangeType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static LedgerEntryChangeType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return LEDGER_ENTRY_CREATED; + case 1: return LEDGER_ENTRY_UPDATED; + case 2: return LEDGER_ENTRY_REMOVED; + case 3: return LEDGER_ENTRY_STATE; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, LedgerEntryChangeType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChanges.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChanges.java new file mode 100644 index 0000000000..1cd780b40a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryChanges.java @@ -0,0 +1,38 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef LedgerEntryChange LedgerEntryChanges<>; + +// =========================================================================== +public class LedgerEntryChanges { + private LedgerEntryChange[] LedgerEntryChanges; + public LedgerEntryChange[] getLedgerEntryChanges() { + return this.LedgerEntryChanges; + } + public void setLedgerEntryChanges(LedgerEntryChange[] value) { + this.LedgerEntryChanges = value; + } + public static void encode(XdrDataOutputStream stream, LedgerEntryChanges encodedLedgerEntryChanges) throws IOException { + int LedgerEntryChangessize = encodedLedgerEntryChanges.getLedgerEntryChanges().length; + stream.writeInt(LedgerEntryChangessize); + for (int i = 0; i < LedgerEntryChangessize; i++) { + LedgerEntryChange.encode(stream, encodedLedgerEntryChanges.LedgerEntryChanges[i]); + } + } + public static LedgerEntryChanges decode(XdrDataInputStream stream) throws IOException { + LedgerEntryChanges decodedLedgerEntryChanges = new LedgerEntryChanges(); + int LedgerEntryChangessize = stream.readInt(); + decodedLedgerEntryChanges.LedgerEntryChanges = new LedgerEntryChange[LedgerEntryChangessize]; + for (int i = 0; i < LedgerEntryChangessize; i++) { + decodedLedgerEntryChanges.LedgerEntryChanges[i] = LedgerEntryChange.decode(stream); + } + return decodedLedgerEntryChanges; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryType.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryType.java new file mode 100644 index 0000000000..6025e1aeb1 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerEntryType.java @@ -0,0 +1,51 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum LedgerEntryType +// { +// ACCOUNT = 0, +// TRUSTLINE = 1, +// OFFER = 2, +// DATA = 3 +// }; + +// =========================================================================== +public enum LedgerEntryType { + ACCOUNT(0), + TRUSTLINE(1), + OFFER(2), + DATA(3), + ; + private int mValue; + + LedgerEntryType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static LedgerEntryType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return ACCOUNT; + case 1: return TRUSTLINE; + case 2: return OFFER; + case 3: return DATA; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, LedgerEntryType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerHeader.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerHeader.java new file mode 100644 index 0000000000..2da8e7534f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerHeader.java @@ -0,0 +1,229 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct LedgerHeader +// { +// uint32 ledgerVersion; // the protocol version of the ledger +// Hash previousLedgerHash; // hash of the previous ledger header +// StellarValue scpValue; // what consensus agreed to +// Hash txSetResultHash; // the TransactionResultSet that led to this ledger +// Hash bucketListHash; // hash of the ledger state +// +// uint32 ledgerSeq; // sequence number of this ledger +// +// int64 totalCoins; // total number of stroops in existence. +// // 10,000,000 stroops in 1 XLM +// +// int64 feePool; // fees burned since last inflation run +// uint32 inflationSeq; // inflation sequence number +// +// uint64 idPool; // last used global ID, used for generating objects +// +// uint32 baseFee; // base fee per operation in stroops +// uint32 baseReserve; // account base reserve in stroops +// +// uint32 maxTxSetSize; // maximum size a transaction set can be +// +// Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back +// // in time without walking the chain back ledger by ledger +// // each slot contains the oldest ledger that is mod of +// // either 50 5000 50000 or 500000 depending on index +// // skipList[0] mod(50), skipList[1] mod(5000), etc +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class LedgerHeader { + public LedgerHeader () {} + private Uint32 ledgerVersion; + public Uint32 getLedgerVersion() { + return this.ledgerVersion; + } + public void setLedgerVersion(Uint32 value) { + this.ledgerVersion = value; + } + private Hash previousLedgerHash; + public Hash getPreviousLedgerHash() { + return this.previousLedgerHash; + } + public void setPreviousLedgerHash(Hash value) { + this.previousLedgerHash = value; + } + private StellarValue scpValue; + public StellarValue getScpValue() { + return this.scpValue; + } + public void setScpValue(StellarValue value) { + this.scpValue = value; + } + private Hash txSetResultHash; + public Hash getTxSetResultHash() { + return this.txSetResultHash; + } + public void setTxSetResultHash(Hash value) { + this.txSetResultHash = value; + } + private Hash bucketListHash; + public Hash getBucketListHash() { + return this.bucketListHash; + } + public void setBucketListHash(Hash value) { + this.bucketListHash = value; + } + private Uint32 ledgerSeq; + public Uint32 getLedgerSeq() { + return this.ledgerSeq; + } + public void setLedgerSeq(Uint32 value) { + this.ledgerSeq = value; + } + private Int64 totalCoins; + public Int64 getTotalCoins() { + return this.totalCoins; + } + public void setTotalCoins(Int64 value) { + this.totalCoins = value; + } + private Int64 feePool; + public Int64 getFeePool() { + return this.feePool; + } + public void setFeePool(Int64 value) { + this.feePool = value; + } + private Uint32 inflationSeq; + public Uint32 getInflationSeq() { + return this.inflationSeq; + } + public void setInflationSeq(Uint32 value) { + this.inflationSeq = value; + } + private Uint64 idPool; + public Uint64 getIdPool() { + return this.idPool; + } + public void setIdPool(Uint64 value) { + this.idPool = value; + } + private Uint32 baseFee; + public Uint32 getBaseFee() { + return this.baseFee; + } + public void setBaseFee(Uint32 value) { + this.baseFee = value; + } + private Uint32 baseReserve; + public Uint32 getBaseReserve() { + return this.baseReserve; + } + public void setBaseReserve(Uint32 value) { + this.baseReserve = value; + } + private Uint32 maxTxSetSize; + public Uint32 getMaxTxSetSize() { + return this.maxTxSetSize; + } + public void setMaxTxSetSize(Uint32 value) { + this.maxTxSetSize = value; + } + private Hash[] skipList; + public Hash[] getSkipList() { + return this.skipList; + } + public void setSkipList(Hash[] value) { + this.skipList = value; + } + private LedgerHeaderExt ext; + public LedgerHeaderExt getExt() { + return this.ext; + } + public void setExt(LedgerHeaderExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, LedgerHeader encodedLedgerHeader) throws IOException{ + Uint32.encode(stream, encodedLedgerHeader.ledgerVersion); + Hash.encode(stream, encodedLedgerHeader.previousLedgerHash); + StellarValue.encode(stream, encodedLedgerHeader.scpValue); + Hash.encode(stream, encodedLedgerHeader.txSetResultHash); + Hash.encode(stream, encodedLedgerHeader.bucketListHash); + Uint32.encode(stream, encodedLedgerHeader.ledgerSeq); + Int64.encode(stream, encodedLedgerHeader.totalCoins); + Int64.encode(stream, encodedLedgerHeader.feePool); + Uint32.encode(stream, encodedLedgerHeader.inflationSeq); + Uint64.encode(stream, encodedLedgerHeader.idPool); + Uint32.encode(stream, encodedLedgerHeader.baseFee); + Uint32.encode(stream, encodedLedgerHeader.baseReserve); + Uint32.encode(stream, encodedLedgerHeader.maxTxSetSize); + int skipListsize = encodedLedgerHeader.getSkipList().length; + for (int i = 0; i < skipListsize; i++) { + Hash.encode(stream, encodedLedgerHeader.skipList[i]); + } + LedgerHeaderExt.encode(stream, encodedLedgerHeader.ext); + } + public static LedgerHeader decode(XdrDataInputStream stream) throws IOException { + LedgerHeader decodedLedgerHeader = new LedgerHeader(); + decodedLedgerHeader.ledgerVersion = Uint32.decode(stream); + decodedLedgerHeader.previousLedgerHash = Hash.decode(stream); + decodedLedgerHeader.scpValue = StellarValue.decode(stream); + decodedLedgerHeader.txSetResultHash = Hash.decode(stream); + decodedLedgerHeader.bucketListHash = Hash.decode(stream); + decodedLedgerHeader.ledgerSeq = Uint32.decode(stream); + decodedLedgerHeader.totalCoins = Int64.decode(stream); + decodedLedgerHeader.feePool = Int64.decode(stream); + decodedLedgerHeader.inflationSeq = Uint32.decode(stream); + decodedLedgerHeader.idPool = Uint64.decode(stream); + decodedLedgerHeader.baseFee = Uint32.decode(stream); + decodedLedgerHeader.baseReserve = Uint32.decode(stream); + decodedLedgerHeader.maxTxSetSize = Uint32.decode(stream); + int skipListsize = 4; + decodedLedgerHeader.skipList = new Hash[skipListsize]; + for (int i = 0; i < skipListsize; i++) { + decodedLedgerHeader.skipList[i] = Hash.decode(stream); + } + decodedLedgerHeader.ext = LedgerHeaderExt.decode(stream); + return decodedLedgerHeader; + } + + public static class LedgerHeaderExt { + public LedgerHeaderExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, LedgerHeaderExt encodedLedgerHeaderExt) throws IOException { + stream.writeInt(encodedLedgerHeaderExt.getDiscriminant().intValue()); + switch (encodedLedgerHeaderExt.getDiscriminant()) { + case 0: + break; + } + } + public static LedgerHeaderExt decode(XdrDataInputStream stream) throws IOException { + LedgerHeaderExt decodedLedgerHeaderExt = new LedgerHeaderExt(); + Integer discriminant = stream.readInt(); + decodedLedgerHeaderExt.setDiscriminant(discriminant); + switch (decodedLedgerHeaderExt.getDiscriminant()) { + case 0: + break; + } + return decodedLedgerHeaderExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerHeaderHistoryEntry.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerHeaderHistoryEntry.java new file mode 100644 index 0000000000..042c4bd281 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerHeaderHistoryEntry.java @@ -0,0 +1,90 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct LedgerHeaderHistoryEntry +// { +// Hash hash; +// LedgerHeader header; +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class LedgerHeaderHistoryEntry { + public LedgerHeaderHistoryEntry () {} + private Hash hash; + public Hash getHash() { + return this.hash; + } + public void setHash(Hash value) { + this.hash = value; + } + private LedgerHeader header; + public LedgerHeader getHeader() { + return this.header; + } + public void setHeader(LedgerHeader value) { + this.header = value; + } + private LedgerHeaderHistoryEntryExt ext; + public LedgerHeaderHistoryEntryExt getExt() { + return this.ext; + } + public void setExt(LedgerHeaderHistoryEntryExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, LedgerHeaderHistoryEntry encodedLedgerHeaderHistoryEntry) throws IOException{ + Hash.encode(stream, encodedLedgerHeaderHistoryEntry.hash); + LedgerHeader.encode(stream, encodedLedgerHeaderHistoryEntry.header); + LedgerHeaderHistoryEntryExt.encode(stream, encodedLedgerHeaderHistoryEntry.ext); + } + public static LedgerHeaderHistoryEntry decode(XdrDataInputStream stream) throws IOException { + LedgerHeaderHistoryEntry decodedLedgerHeaderHistoryEntry = new LedgerHeaderHistoryEntry(); + decodedLedgerHeaderHistoryEntry.hash = Hash.decode(stream); + decodedLedgerHeaderHistoryEntry.header = LedgerHeader.decode(stream); + decodedLedgerHeaderHistoryEntry.ext = LedgerHeaderHistoryEntryExt.decode(stream); + return decodedLedgerHeaderHistoryEntry; + } + + public static class LedgerHeaderHistoryEntryExt { + public LedgerHeaderHistoryEntryExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, LedgerHeaderHistoryEntryExt encodedLedgerHeaderHistoryEntryExt) throws IOException { + stream.writeInt(encodedLedgerHeaderHistoryEntryExt.getDiscriminant().intValue()); + switch (encodedLedgerHeaderHistoryEntryExt.getDiscriminant()) { + case 0: + break; + } + } + public static LedgerHeaderHistoryEntryExt decode(XdrDataInputStream stream) throws IOException { + LedgerHeaderHistoryEntryExt decodedLedgerHeaderHistoryEntryExt = new LedgerHeaderHistoryEntryExt(); + Integer discriminant = stream.readInt(); + decodedLedgerHeaderHistoryEntryExt.setDiscriminant(discriminant); + switch (decodedLedgerHeaderHistoryEntryExt.getDiscriminant()) { + case 0: + break; + } + return decodedLedgerHeaderHistoryEntryExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerKey.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerKey.java new file mode 100644 index 0000000000..514556fdae --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerKey.java @@ -0,0 +1,220 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union LedgerKey switch (LedgerEntryType type) +// { +// case ACCOUNT: +// struct +// { +// AccountID accountID; +// } account; +// +// case TRUSTLINE: +// struct +// { +// AccountID accountID; +// Asset asset; +// } trustLine; +// +// case OFFER: +// struct +// { +// AccountID sellerID; +// uint64 offerID; +// } offer; +// +// case DATA: +// struct +// { +// AccountID accountID; +// string64 dataName; +// } data; +// }; + +// =========================================================================== +public class LedgerKey { + public LedgerKey () {} + LedgerEntryType type; + public LedgerEntryType getDiscriminant() { + return this.type; + } + public void setDiscriminant(LedgerEntryType value) { + this.type = value; + } + private LedgerKeyAccount account; + public LedgerKeyAccount getAccount() { + return this.account; + } + public void setAccount(LedgerKeyAccount value) { + this.account = value; + } + private LedgerKeyTrustLine trustLine; + public LedgerKeyTrustLine getTrustLine() { + return this.trustLine; + } + public void setTrustLine(LedgerKeyTrustLine value) { + this.trustLine = value; + } + private LedgerKeyOffer offer; + public LedgerKeyOffer getOffer() { + return this.offer; + } + public void setOffer(LedgerKeyOffer value) { + this.offer = value; + } + private LedgerKeyData data; + public LedgerKeyData getData() { + return this.data; + } + public void setData(LedgerKeyData value) { + this.data = value; + } + public static void encode(XdrDataOutputStream stream, LedgerKey encodedLedgerKey) throws IOException { + stream.writeInt(encodedLedgerKey.getDiscriminant().getValue()); + switch (encodedLedgerKey.getDiscriminant()) { + case ACCOUNT: + LedgerKeyAccount.encode(stream, encodedLedgerKey.account); + break; + case TRUSTLINE: + LedgerKeyTrustLine.encode(stream, encodedLedgerKey.trustLine); + break; + case OFFER: + LedgerKeyOffer.encode(stream, encodedLedgerKey.offer); + break; + case DATA: + LedgerKeyData.encode(stream, encodedLedgerKey.data); + break; + } + } + public static LedgerKey decode(XdrDataInputStream stream) throws IOException { + LedgerKey decodedLedgerKey = new LedgerKey(); + LedgerEntryType discriminant = LedgerEntryType.decode(stream); + decodedLedgerKey.setDiscriminant(discriminant); + switch (decodedLedgerKey.getDiscriminant()) { + case ACCOUNT: + decodedLedgerKey.account = LedgerKeyAccount.decode(stream); + break; + case TRUSTLINE: + decodedLedgerKey.trustLine = LedgerKeyTrustLine.decode(stream); + break; + case OFFER: + decodedLedgerKey.offer = LedgerKeyOffer.decode(stream); + break; + case DATA: + decodedLedgerKey.data = LedgerKeyData.decode(stream); + break; + } + return decodedLedgerKey; + } + + public static class LedgerKeyAccount { + public LedgerKeyAccount () {} + private AccountID accountID; + public AccountID getAccountID() { + return this.accountID; + } + public void setAccountID(AccountID value) { + this.accountID = value; + } + public static void encode(XdrDataOutputStream stream, LedgerKeyAccount encodedLedgerKeyAccount) throws IOException{ + AccountID.encode(stream, encodedLedgerKeyAccount.accountID); + } + public static LedgerKeyAccount decode(XdrDataInputStream stream) throws IOException { + LedgerKeyAccount decodedLedgerKeyAccount = new LedgerKeyAccount(); + decodedLedgerKeyAccount.accountID = AccountID.decode(stream); + return decodedLedgerKeyAccount; + } + + } + public static class LedgerKeyTrustLine { + public LedgerKeyTrustLine () {} + private AccountID accountID; + public AccountID getAccountID() { + return this.accountID; + } + public void setAccountID(AccountID value) { + this.accountID = value; + } + private Asset asset; + public Asset getAsset() { + return this.asset; + } + public void setAsset(Asset value) { + this.asset = value; + } + public static void encode(XdrDataOutputStream stream, LedgerKeyTrustLine encodedLedgerKeyTrustLine) throws IOException{ + AccountID.encode(stream, encodedLedgerKeyTrustLine.accountID); + Asset.encode(stream, encodedLedgerKeyTrustLine.asset); + } + public static LedgerKeyTrustLine decode(XdrDataInputStream stream) throws IOException { + LedgerKeyTrustLine decodedLedgerKeyTrustLine = new LedgerKeyTrustLine(); + decodedLedgerKeyTrustLine.accountID = AccountID.decode(stream); + decodedLedgerKeyTrustLine.asset = Asset.decode(stream); + return decodedLedgerKeyTrustLine; + } + + } + public static class LedgerKeyOffer { + public LedgerKeyOffer () {} + private AccountID sellerID; + public AccountID getSellerID() { + return this.sellerID; + } + public void setSellerID(AccountID value) { + this.sellerID = value; + } + private Uint64 offerID; + public Uint64 getOfferID() { + return this.offerID; + } + public void setOfferID(Uint64 value) { + this.offerID = value; + } + public static void encode(XdrDataOutputStream stream, LedgerKeyOffer encodedLedgerKeyOffer) throws IOException{ + AccountID.encode(stream, encodedLedgerKeyOffer.sellerID); + Uint64.encode(stream, encodedLedgerKeyOffer.offerID); + } + public static LedgerKeyOffer decode(XdrDataInputStream stream) throws IOException { + LedgerKeyOffer decodedLedgerKeyOffer = new LedgerKeyOffer(); + decodedLedgerKeyOffer.sellerID = AccountID.decode(stream); + decodedLedgerKeyOffer.offerID = Uint64.decode(stream); + return decodedLedgerKeyOffer; + } + + } + public static class LedgerKeyData { + public LedgerKeyData () {} + private AccountID accountID; + public AccountID getAccountID() { + return this.accountID; + } + public void setAccountID(AccountID value) { + this.accountID = value; + } + private String64 dataName; + public String64 getDataName() { + return this.dataName; + } + public void setDataName(String64 value) { + this.dataName = value; + } + public static void encode(XdrDataOutputStream stream, LedgerKeyData encodedLedgerKeyData) throws IOException{ + AccountID.encode(stream, encodedLedgerKeyData.accountID); + String64.encode(stream, encodedLedgerKeyData.dataName); + } + public static LedgerKeyData decode(XdrDataInputStream stream) throws IOException { + LedgerKeyData decodedLedgerKeyData = new LedgerKeyData(); + decodedLedgerKeyData.accountID = AccountID.decode(stream); + decodedLedgerKeyData.dataName = String64.decode(stream); + return decodedLedgerKeyData; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerSCPMessages.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerSCPMessages.java new file mode 100644 index 0000000000..7ce1de763f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerSCPMessages.java @@ -0,0 +1,52 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct LedgerSCPMessages +// { +// uint32 ledgerSeq; +// SCPEnvelope messages<>; +// }; + +// =========================================================================== +public class LedgerSCPMessages { + public LedgerSCPMessages () {} + private Uint32 ledgerSeq; + public Uint32 getLedgerSeq() { + return this.ledgerSeq; + } + public void setLedgerSeq(Uint32 value) { + this.ledgerSeq = value; + } + private SCPEnvelope[] messages; + public SCPEnvelope[] getMessages() { + return this.messages; + } + public void setMessages(SCPEnvelope[] value) { + this.messages = value; + } + public static void encode(XdrDataOutputStream stream, LedgerSCPMessages encodedLedgerSCPMessages) throws IOException{ + Uint32.encode(stream, encodedLedgerSCPMessages.ledgerSeq); + int messagessize = encodedLedgerSCPMessages.getMessages().length; + stream.writeInt(messagessize); + for (int i = 0; i < messagessize; i++) { + SCPEnvelope.encode(stream, encodedLedgerSCPMessages.messages[i]); + } + } + public static LedgerSCPMessages decode(XdrDataInputStream stream) throws IOException { + LedgerSCPMessages decodedLedgerSCPMessages = new LedgerSCPMessages(); + decodedLedgerSCPMessages.ledgerSeq = Uint32.decode(stream); + int messagessize = stream.readInt(); + decodedLedgerSCPMessages.messages = new SCPEnvelope[messagessize]; + for (int i = 0; i < messagessize; i++) { + decodedLedgerSCPMessages.messages[i] = SCPEnvelope.decode(stream); + } + return decodedLedgerSCPMessages; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerUpgrade.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerUpgrade.java new file mode 100644 index 0000000000..662c302aa1 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerUpgrade.java @@ -0,0 +1,98 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union LedgerUpgrade switch (LedgerUpgradeType type) +// { +// case LEDGER_UPGRADE_VERSION: +// uint32 newLedgerVersion; // update ledgerVersion +// case LEDGER_UPGRADE_BASE_FEE: +// uint32 newBaseFee; // update baseFee +// case LEDGER_UPGRADE_MAX_TX_SET_SIZE: +// uint32 newMaxTxSetSize; // update maxTxSetSize +// case LEDGER_UPGRADE_BASE_RESERVE: +// uint32 newBaseReserve; // update baseReserve +// }; + +// =========================================================================== +public class LedgerUpgrade { + public LedgerUpgrade () {} + LedgerUpgradeType type; + public LedgerUpgradeType getDiscriminant() { + return this.type; + } + public void setDiscriminant(LedgerUpgradeType value) { + this.type = value; + } + private Uint32 newLedgerVersion; + public Uint32 getNewLedgerVersion() { + return this.newLedgerVersion; + } + public void setNewLedgerVersion(Uint32 value) { + this.newLedgerVersion = value; + } + private Uint32 newBaseFee; + public Uint32 getNewBaseFee() { + return this.newBaseFee; + } + public void setNewBaseFee(Uint32 value) { + this.newBaseFee = value; + } + private Uint32 newMaxTxSetSize; + public Uint32 getNewMaxTxSetSize() { + return this.newMaxTxSetSize; + } + public void setNewMaxTxSetSize(Uint32 value) { + this.newMaxTxSetSize = value; + } + private Uint32 newBaseReserve; + public Uint32 getNewBaseReserve() { + return this.newBaseReserve; + } + public void setNewBaseReserve(Uint32 value) { + this.newBaseReserve = value; + } + public static void encode(XdrDataOutputStream stream, LedgerUpgrade encodedLedgerUpgrade) throws IOException { + stream.writeInt(encodedLedgerUpgrade.getDiscriminant().getValue()); + switch (encodedLedgerUpgrade.getDiscriminant()) { + case LEDGER_UPGRADE_VERSION: + Uint32.encode(stream, encodedLedgerUpgrade.newLedgerVersion); + break; + case LEDGER_UPGRADE_BASE_FEE: + Uint32.encode(stream, encodedLedgerUpgrade.newBaseFee); + break; + case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + Uint32.encode(stream, encodedLedgerUpgrade.newMaxTxSetSize); + break; + case LEDGER_UPGRADE_BASE_RESERVE: + Uint32.encode(stream, encodedLedgerUpgrade.newBaseReserve); + break; + } + } + public static LedgerUpgrade decode(XdrDataInputStream stream) throws IOException { + LedgerUpgrade decodedLedgerUpgrade = new LedgerUpgrade(); + LedgerUpgradeType discriminant = LedgerUpgradeType.decode(stream); + decodedLedgerUpgrade.setDiscriminant(discriminant); + switch (decodedLedgerUpgrade.getDiscriminant()) { + case LEDGER_UPGRADE_VERSION: + decodedLedgerUpgrade.newLedgerVersion = Uint32.decode(stream); + break; + case LEDGER_UPGRADE_BASE_FEE: + decodedLedgerUpgrade.newBaseFee = Uint32.decode(stream); + break; + case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + decodedLedgerUpgrade.newMaxTxSetSize = Uint32.decode(stream); + break; + case LEDGER_UPGRADE_BASE_RESERVE: + decodedLedgerUpgrade.newBaseReserve = Uint32.decode(stream); + break; + } + return decodedLedgerUpgrade; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/LedgerUpgradeType.java b/app/src/main/java/org/stellar/sdk/xdr/LedgerUpgradeType.java new file mode 100644 index 0000000000..577e019e38 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/LedgerUpgradeType.java @@ -0,0 +1,51 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum LedgerUpgradeType +// { +// LEDGER_UPGRADE_VERSION = 1, +// LEDGER_UPGRADE_BASE_FEE = 2, +// LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, +// LEDGER_UPGRADE_BASE_RESERVE = 4 +// }; + +// =========================================================================== +public enum LedgerUpgradeType { + LEDGER_UPGRADE_VERSION(1), + LEDGER_UPGRADE_BASE_FEE(2), + LEDGER_UPGRADE_MAX_TX_SET_SIZE(3), + LEDGER_UPGRADE_BASE_RESERVE(4), + ; + private int mValue; + + LedgerUpgradeType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static LedgerUpgradeType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 1: return LEDGER_UPGRADE_VERSION; + case 2: return LEDGER_UPGRADE_BASE_FEE; + case 3: return LEDGER_UPGRADE_MAX_TX_SET_SIZE; + case 4: return LEDGER_UPGRADE_BASE_RESERVE; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, LedgerUpgradeType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Liabilities.java b/app/src/main/java/org/stellar/sdk/xdr/Liabilities.java new file mode 100644 index 0000000000..231e46f17d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Liabilities.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Liabilities +// { +// int64 buying; +// int64 selling; +// }; + +// =========================================================================== +public class Liabilities { + public Liabilities () {} + private Int64 buying; + public Int64 getBuying() { + return this.buying; + } + public void setBuying(Int64 value) { + this.buying = value; + } + private Int64 selling; + public Int64 getSelling() { + return this.selling; + } + public void setSelling(Int64 value) { + this.selling = value; + } + public static void encode(XdrDataOutputStream stream, Liabilities encodedLiabilities) throws IOException{ + Int64.encode(stream, encodedLiabilities.buying); + Int64.encode(stream, encodedLiabilities.selling); + } + public static Liabilities decode(XdrDataInputStream stream) throws IOException { + Liabilities decodedLiabilities = new Liabilities(); + decodedLiabilities.buying = Int64.decode(stream); + decodedLiabilities.selling = Int64.decode(stream); + return decodedLiabilities; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ManageDataOp.java b/app/src/main/java/org/stellar/sdk/xdr/ManageDataOp.java new file mode 100644 index 0000000000..943c53df3b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ManageDataOp.java @@ -0,0 +1,52 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct ManageDataOp +// { +// string64 dataName; +// DataValue* dataValue; // set to null to clear +// }; + +// =========================================================================== +public class ManageDataOp { + public ManageDataOp () {} + private String64 dataName; + public String64 getDataName() { + return this.dataName; + } + public void setDataName(String64 value) { + this.dataName = value; + } + private DataValue dataValue; + public DataValue getDataValue() { + return this.dataValue; + } + public void setDataValue(DataValue value) { + this.dataValue = value; + } + public static void encode(XdrDataOutputStream stream, ManageDataOp encodedManageDataOp) throws IOException{ + String64.encode(stream, encodedManageDataOp.dataName); + if (encodedManageDataOp.dataValue != null) { + stream.writeInt(1); + DataValue.encode(stream, encodedManageDataOp.dataValue); + } else { + stream.writeInt(0); + } + } + public static ManageDataOp decode(XdrDataInputStream stream) throws IOException { + ManageDataOp decodedManageDataOp = new ManageDataOp(); + decodedManageDataOp.dataName = String64.decode(stream); + int dataValuePresent = stream.readInt(); + if (dataValuePresent != 0) { + decodedManageDataOp.dataValue = DataValue.decode(stream); + } + return decodedManageDataOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ManageDataResult.java b/app/src/main/java/org/stellar/sdk/xdr/ManageDataResult.java new file mode 100644 index 0000000000..6aa5198cc3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ManageDataResult.java @@ -0,0 +1,50 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union ManageDataResult switch (ManageDataResultCode code) +// { +// case MANAGE_DATA_SUCCESS: +// void; +// default: +// void; +// }; + +// =========================================================================== +public class ManageDataResult { + public ManageDataResult () {} + ManageDataResultCode code; + public ManageDataResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(ManageDataResultCode value) { + this.code = value; + } + public static void encode(XdrDataOutputStream stream, ManageDataResult encodedManageDataResult) throws IOException { + stream.writeInt(encodedManageDataResult.getDiscriminant().getValue()); + switch (encodedManageDataResult.getDiscriminant()) { + case MANAGE_DATA_SUCCESS: + break; + default: + break; + } + } + public static ManageDataResult decode(XdrDataInputStream stream) throws IOException { + ManageDataResult decodedManageDataResult = new ManageDataResult(); + ManageDataResultCode discriminant = ManageDataResultCode.decode(stream); + decodedManageDataResult.setDiscriminant(discriminant); + switch (decodedManageDataResult.getDiscriminant()) { + case MANAGE_DATA_SUCCESS: + break; + default: + break; + } + return decodedManageDataResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ManageDataResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/ManageDataResultCode.java new file mode 100644 index 0000000000..8f10f7c86e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ManageDataResultCode.java @@ -0,0 +1,58 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum ManageDataResultCode +// { +// // codes considered as "success" for the operation +// MANAGE_DATA_SUCCESS = 0, +// // codes considered as "failure" for the operation +// MANAGE_DATA_NOT_SUPPORTED_YET = +// -1, // The network hasn't moved to this protocol change yet +// MANAGE_DATA_NAME_NOT_FOUND = +// -2, // Trying to remove a Data Entry that isn't there +// MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry +// MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string +// }; + +// =========================================================================== +public enum ManageDataResultCode { + MANAGE_DATA_SUCCESS(0), + MANAGE_DATA_NOT_SUPPORTED_YET(-1), + MANAGE_DATA_NAME_NOT_FOUND(-2), + MANAGE_DATA_LOW_RESERVE(-3), + MANAGE_DATA_INVALID_NAME(-4), + ; + private int mValue; + + ManageDataResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static ManageDataResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return MANAGE_DATA_SUCCESS; + case -1: return MANAGE_DATA_NOT_SUPPORTED_YET; + case -2: return MANAGE_DATA_NAME_NOT_FOUND; + case -3: return MANAGE_DATA_LOW_RESERVE; + case -4: return MANAGE_DATA_INVALID_NAME; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, ManageDataResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ManageOfferEffect.java b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferEffect.java new file mode 100644 index 0000000000..7956d4d9f1 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferEffect.java @@ -0,0 +1,48 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum ManageOfferEffect +// { +// MANAGE_OFFER_CREATED = 0, +// MANAGE_OFFER_UPDATED = 1, +// MANAGE_OFFER_DELETED = 2 +// }; + +// =========================================================================== +public enum ManageOfferEffect { + MANAGE_OFFER_CREATED(0), + MANAGE_OFFER_UPDATED(1), + MANAGE_OFFER_DELETED(2), + ; + private int mValue; + + ManageOfferEffect(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static ManageOfferEffect decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return MANAGE_OFFER_CREATED; + case 1: return MANAGE_OFFER_UPDATED; + case 2: return MANAGE_OFFER_DELETED; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, ManageOfferEffect value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ManageOfferOp.java b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferOp.java new file mode 100644 index 0000000000..b0567771a3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferOp.java @@ -0,0 +1,76 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct ManageOfferOp +// { +// Asset selling; +// Asset buying; +// int64 amount; // amount being sold. if set to 0, delete the offer +// Price price; // price of thing being sold in terms of what you are buying +// +// // 0=create a new offer, otherwise edit an existing offer +// uint64 offerID; +// }; + +// =========================================================================== +public class ManageOfferOp { + public ManageOfferOp () {} + private Asset selling; + public Asset getSelling() { + return this.selling; + } + public void setSelling(Asset value) { + this.selling = value; + } + private Asset buying; + public Asset getBuying() { + return this.buying; + } + public void setBuying(Asset value) { + this.buying = value; + } + private Int64 amount; + public Int64 getAmount() { + return this.amount; + } + public void setAmount(Int64 value) { + this.amount = value; + } + private Price price; + public Price getPrice() { + return this.price; + } + public void setPrice(Price value) { + this.price = value; + } + private Uint64 offerID; + public Uint64 getOfferID() { + return this.offerID; + } + public void setOfferID(Uint64 value) { + this.offerID = value; + } + public static void encode(XdrDataOutputStream stream, ManageOfferOp encodedManageOfferOp) throws IOException{ + Asset.encode(stream, encodedManageOfferOp.selling); + Asset.encode(stream, encodedManageOfferOp.buying); + Int64.encode(stream, encodedManageOfferOp.amount); + Price.encode(stream, encodedManageOfferOp.price); + Uint64.encode(stream, encodedManageOfferOp.offerID); + } + public static ManageOfferOp decode(XdrDataInputStream stream) throws IOException { + ManageOfferOp decodedManageOfferOp = new ManageOfferOp(); + decodedManageOfferOp.selling = Asset.decode(stream); + decodedManageOfferOp.buying = Asset.decode(stream); + decodedManageOfferOp.amount = Int64.decode(stream); + decodedManageOfferOp.price = Price.decode(stream); + decodedManageOfferOp.offerID = Uint64.decode(stream); + return decodedManageOfferOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ManageOfferResult.java b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferResult.java new file mode 100644 index 0000000000..8988e7de40 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferResult.java @@ -0,0 +1,59 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union ManageOfferResult switch (ManageOfferResultCode code) +// { +// case MANAGE_OFFER_SUCCESS: +// ManageOfferSuccessResult success; +// default: +// void; +// }; + +// =========================================================================== +public class ManageOfferResult { + public ManageOfferResult () {} + ManageOfferResultCode code; + public ManageOfferResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(ManageOfferResultCode value) { + this.code = value; + } + private ManageOfferSuccessResult success; + public ManageOfferSuccessResult getSuccess() { + return this.success; + } + public void setSuccess(ManageOfferSuccessResult value) { + this.success = value; + } + public static void encode(XdrDataOutputStream stream, ManageOfferResult encodedManageOfferResult) throws IOException { + stream.writeInt(encodedManageOfferResult.getDiscriminant().getValue()); + switch (encodedManageOfferResult.getDiscriminant()) { + case MANAGE_OFFER_SUCCESS: + ManageOfferSuccessResult.encode(stream, encodedManageOfferResult.success); + break; + default: + break; + } + } + public static ManageOfferResult decode(XdrDataInputStream stream) throws IOException { + ManageOfferResult decodedManageOfferResult = new ManageOfferResult(); + ManageOfferResultCode discriminant = ManageOfferResultCode.decode(stream); + decodedManageOfferResult.setDiscriminant(discriminant); + switch (decodedManageOfferResult.getDiscriminant()) { + case MANAGE_OFFER_SUCCESS: + decodedManageOfferResult.success = ManageOfferSuccessResult.decode(stream); + break; + default: + break; + } + return decodedManageOfferResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ManageOfferResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferResultCode.java new file mode 100644 index 0000000000..78b95feb2b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferResultCode.java @@ -0,0 +1,84 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum ManageOfferResultCode +// { +// // codes considered as "success" for the operation +// MANAGE_OFFER_SUCCESS = 0, +// +// // codes considered as "failure" for the operation +// MANAGE_OFFER_MALFORMED = -1, // generated offer would be invalid +// MANAGE_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling +// MANAGE_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying +// MANAGE_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell +// MANAGE_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy +// MANAGE_OFFER_LINE_FULL = -6, // can't receive more of what it's buying +// MANAGE_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell +// MANAGE_OFFER_CROSS_SELF = -8, // would cross an offer from the same user +// MANAGE_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling +// MANAGE_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying +// +// // update errors +// MANAGE_OFFER_NOT_FOUND = -11, // offerID does not match an existing offer +// +// MANAGE_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer +// }; + +// =========================================================================== +public enum ManageOfferResultCode { + MANAGE_OFFER_SUCCESS(0), + MANAGE_OFFER_MALFORMED(-1), + MANAGE_OFFER_SELL_NO_TRUST(-2), + MANAGE_OFFER_BUY_NO_TRUST(-3), + MANAGE_OFFER_SELL_NOT_AUTHORIZED(-4), + MANAGE_OFFER_BUY_NOT_AUTHORIZED(-5), + MANAGE_OFFER_LINE_FULL(-6), + MANAGE_OFFER_UNDERFUNDED(-7), + MANAGE_OFFER_CROSS_SELF(-8), + MANAGE_OFFER_SELL_NO_ISSUER(-9), + MANAGE_OFFER_BUY_NO_ISSUER(-10), + MANAGE_OFFER_NOT_FOUND(-11), + MANAGE_OFFER_LOW_RESERVE(-12), + ; + private int mValue; + + ManageOfferResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static ManageOfferResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return MANAGE_OFFER_SUCCESS; + case -1: return MANAGE_OFFER_MALFORMED; + case -2: return MANAGE_OFFER_SELL_NO_TRUST; + case -3: return MANAGE_OFFER_BUY_NO_TRUST; + case -4: return MANAGE_OFFER_SELL_NOT_AUTHORIZED; + case -5: return MANAGE_OFFER_BUY_NOT_AUTHORIZED; + case -6: return MANAGE_OFFER_LINE_FULL; + case -7: return MANAGE_OFFER_UNDERFUNDED; + case -8: return MANAGE_OFFER_CROSS_SELF; + case -9: return MANAGE_OFFER_SELL_NO_ISSUER; + case -10: return MANAGE_OFFER_BUY_NO_ISSUER; + case -11: return MANAGE_OFFER_NOT_FOUND; + case -12: return MANAGE_OFFER_LOW_RESERVE; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, ManageOfferResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ManageOfferSuccessResult.java b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferSuccessResult.java new file mode 100644 index 0000000000..62bec32e43 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ManageOfferSuccessResult.java @@ -0,0 +1,106 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct ManageOfferSuccessResult +// { +// // offers that got claimed while creating this offer +// ClaimOfferAtom offersClaimed<>; +// +// union switch (ManageOfferEffect effect) +// { +// case MANAGE_OFFER_CREATED: +// case MANAGE_OFFER_UPDATED: +// OfferEntry offer; +// default: +// void; +// } +// offer; +// }; + +// =========================================================================== +public class ManageOfferSuccessResult { + public ManageOfferSuccessResult () {} + private ClaimOfferAtom[] offersClaimed; + public ClaimOfferAtom[] getOffersClaimed() { + return this.offersClaimed; + } + public void setOffersClaimed(ClaimOfferAtom[] value) { + this.offersClaimed = value; + } + private ManageOfferSuccessResultOffer offer; + public ManageOfferSuccessResultOffer getOffer() { + return this.offer; + } + public void setOffer(ManageOfferSuccessResultOffer value) { + this.offer = value; + } + public static void encode(XdrDataOutputStream stream, ManageOfferSuccessResult encodedManageOfferSuccessResult) throws IOException{ + int offersClaimedsize = encodedManageOfferSuccessResult.getOffersClaimed().length; + stream.writeInt(offersClaimedsize); + for (int i = 0; i < offersClaimedsize; i++) { + ClaimOfferAtom.encode(stream, encodedManageOfferSuccessResult.offersClaimed[i]); + } + ManageOfferSuccessResultOffer.encode(stream, encodedManageOfferSuccessResult.offer); + } + public static ManageOfferSuccessResult decode(XdrDataInputStream stream) throws IOException { + ManageOfferSuccessResult decodedManageOfferSuccessResult = new ManageOfferSuccessResult(); + int offersClaimedsize = stream.readInt(); + decodedManageOfferSuccessResult.offersClaimed = new ClaimOfferAtom[offersClaimedsize]; + for (int i = 0; i < offersClaimedsize; i++) { + decodedManageOfferSuccessResult.offersClaimed[i] = ClaimOfferAtom.decode(stream); + } + decodedManageOfferSuccessResult.offer = ManageOfferSuccessResultOffer.decode(stream); + return decodedManageOfferSuccessResult; + } + + public static class ManageOfferSuccessResultOffer { + public ManageOfferSuccessResultOffer () {} + ManageOfferEffect effect; + public ManageOfferEffect getDiscriminant() { + return this.effect; + } + public void setDiscriminant(ManageOfferEffect value) { + this.effect = value; + } + private OfferEntry offer; + public OfferEntry getOffer() { + return this.offer; + } + public void setOffer(OfferEntry value) { + this.offer = value; + } + public static void encode(XdrDataOutputStream stream, ManageOfferSuccessResultOffer encodedManageOfferSuccessResultOffer) throws IOException { + stream.writeInt(encodedManageOfferSuccessResultOffer.getDiscriminant().getValue()); + switch (encodedManageOfferSuccessResultOffer.getDiscriminant()) { + case MANAGE_OFFER_CREATED: + case MANAGE_OFFER_UPDATED: + OfferEntry.encode(stream, encodedManageOfferSuccessResultOffer.offer); + break; + default: + break; + } + } + public static ManageOfferSuccessResultOffer decode(XdrDataInputStream stream) throws IOException { + ManageOfferSuccessResultOffer decodedManageOfferSuccessResultOffer = new ManageOfferSuccessResultOffer(); + ManageOfferEffect discriminant = ManageOfferEffect.decode(stream); + decodedManageOfferSuccessResultOffer.setDiscriminant(discriminant); + switch (decodedManageOfferSuccessResultOffer.getDiscriminant()) { + case MANAGE_OFFER_CREATED: + case MANAGE_OFFER_UPDATED: + decodedManageOfferSuccessResultOffer.offer = OfferEntry.decode(stream); + break; + default: + break; + } + return decodedManageOfferSuccessResultOffer; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Memo.java b/app/src/main/java/org/stellar/sdk/xdr/Memo.java new file mode 100644 index 0000000000..d66c5d2d32 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Memo.java @@ -0,0 +1,104 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union Memo switch (MemoType type) +// { +// case MEMO_NONE: +// void; +// case MEMO_TEXT: +// string text<28>; +// case MEMO_ID: +// uint64 id; +// case MEMO_HASH: +// Hash hash; // the hash of what to pull from the content server +// case MEMO_RETURN: +// Hash retHash; // the hash of the tx you are rejecting +// }; + +// =========================================================================== +public class Memo { + public Memo () {} + MemoType type; + public MemoType getDiscriminant() { + return this.type; + } + public void setDiscriminant(MemoType value) { + this.type = value; + } + private String text; + public String getText() { + return this.text; + } + public void setText(String value) { + this.text = value; + } + private Uint64 id; + public Uint64 getId() { + return this.id; + } + public void setId(Uint64 value) { + this.id = value; + } + private Hash hash; + public Hash getHash() { + return this.hash; + } + public void setHash(Hash value) { + this.hash = value; + } + private Hash retHash; + public Hash getRetHash() { + return this.retHash; + } + public void setRetHash(Hash value) { + this.retHash = value; + } + public static void encode(XdrDataOutputStream stream, Memo encodedMemo) throws IOException { + stream.writeInt(encodedMemo.getDiscriminant().getValue()); + switch (encodedMemo.getDiscriminant()) { + case MEMO_NONE: + break; + case MEMO_TEXT: + stream.writeString(encodedMemo.text); + break; + case MEMO_ID: + Uint64.encode(stream, encodedMemo.id); + break; + case MEMO_HASH: + Hash.encode(stream, encodedMemo.hash); + break; + case MEMO_RETURN: + Hash.encode(stream, encodedMemo.retHash); + break; + } + } + public static Memo decode(XdrDataInputStream stream) throws IOException { + Memo decodedMemo = new Memo(); + MemoType discriminant = MemoType.decode(stream); + decodedMemo.setDiscriminant(discriminant); + switch (decodedMemo.getDiscriminant()) { + case MEMO_NONE: + break; + case MEMO_TEXT: + decodedMemo.text = stream.readString(); + break; + case MEMO_ID: + decodedMemo.id = Uint64.decode(stream); + break; + case MEMO_HASH: + decodedMemo.hash = Hash.decode(stream); + break; + case MEMO_RETURN: + decodedMemo.retHash = Hash.decode(stream); + break; + } + return decodedMemo; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/MemoType.java b/app/src/main/java/org/stellar/sdk/xdr/MemoType.java new file mode 100644 index 0000000000..f08a174536 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/MemoType.java @@ -0,0 +1,54 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum MemoType +// { +// MEMO_NONE = 0, +// MEMO_TEXT = 1, +// MEMO_ID = 2, +// MEMO_HASH = 3, +// MEMO_RETURN = 4 +// }; + +// =========================================================================== +public enum MemoType { + MEMO_NONE(0), + MEMO_TEXT(1), + MEMO_ID(2), + MEMO_HASH(3), + MEMO_RETURN(4), + ; + private int mValue; + + MemoType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static MemoType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return MEMO_NONE; + case 1: return MEMO_TEXT; + case 2: return MEMO_ID; + case 3: return MEMO_HASH; + case 4: return MEMO_RETURN; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, MemoType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/MessageType.java b/app/src/main/java/org/stellar/sdk/xdr/MessageType.java new file mode 100644 index 0000000000..6e69483097 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/MessageType.java @@ -0,0 +1,85 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum MessageType +// { +// ERROR_MSG = 0, +// AUTH = 2, +// DONT_HAVE = 3, +// +// GET_PEERS = 4, // gets a list of peers this guy knows about +// PEERS = 5, +// +// GET_TX_SET = 6, // gets a particular txset by hash +// TX_SET = 7, +// +// TRANSACTION = 8, // pass on a tx you have heard about +// +// // SCP +// GET_SCP_QUORUMSET = 9, +// SCP_QUORUMSET = 10, +// SCP_MESSAGE = 11, +// GET_SCP_STATE = 12, +// +// // new messages +// HELLO = 13 +// }; + +// =========================================================================== +public enum MessageType { + ERROR_MSG(0), + AUTH(2), + DONT_HAVE(3), + GET_PEERS(4), + PEERS(5), + GET_TX_SET(6), + TX_SET(7), + TRANSACTION(8), + GET_SCP_QUORUMSET(9), + SCP_QUORUMSET(10), + SCP_MESSAGE(11), + GET_SCP_STATE(12), + HELLO(13), + ; + private int mValue; + + MessageType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static MessageType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return ERROR_MSG; + case 2: return AUTH; + case 3: return DONT_HAVE; + case 4: return GET_PEERS; + case 5: return PEERS; + case 6: return GET_TX_SET; + case 7: return TX_SET; + case 8: return TRANSACTION; + case 9: return GET_SCP_QUORUMSET; + case 10: return SCP_QUORUMSET; + case 11: return SCP_MESSAGE; + case 12: return GET_SCP_STATE; + case 13: return HELLO; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, MessageType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/NodeID.java b/app/src/main/java/org/stellar/sdk/xdr/NodeID.java new file mode 100644 index 0000000000..20244af461 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/NodeID.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef PublicKey NodeID; + +// =========================================================================== +public class NodeID { + private PublicKey NodeID; + public PublicKey getNodeID() { + return this.NodeID; + } + public void setNodeID(PublicKey value) { + this.NodeID = value; + } + public static void encode(XdrDataOutputStream stream, NodeID encodedNodeID) throws IOException { + PublicKey.encode(stream, encodedNodeID.NodeID); + } + public static NodeID decode(XdrDataInputStream stream) throws IOException { + NodeID decodedNodeID = new NodeID(); + decodedNodeID.NodeID = PublicKey.decode(stream); + return decodedNodeID; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/OfferEntry.java b/app/src/main/java/org/stellar/sdk/xdr/OfferEntry.java new file mode 100644 index 0000000000..cac099166c --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/OfferEntry.java @@ -0,0 +1,146 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct OfferEntry +// { +// AccountID sellerID; +// uint64 offerID; +// Asset selling; // A +// Asset buying; // B +// int64 amount; // amount of A +// +// /* price for this offer: +// price of A in terms of B +// price=AmountB/AmountA=priceNumerator/priceDenominator +// price is after fees +// */ +// Price price; +// uint32 flags; // see OfferEntryFlags +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class OfferEntry { + public OfferEntry () {} + private AccountID sellerID; + public AccountID getSellerID() { + return this.sellerID; + } + public void setSellerID(AccountID value) { + this.sellerID = value; + } + private Uint64 offerID; + public Uint64 getOfferID() { + return this.offerID; + } + public void setOfferID(Uint64 value) { + this.offerID = value; + } + private Asset selling; + public Asset getSelling() { + return this.selling; + } + public void setSelling(Asset value) { + this.selling = value; + } + private Asset buying; + public Asset getBuying() { + return this.buying; + } + public void setBuying(Asset value) { + this.buying = value; + } + private Int64 amount; + public Int64 getAmount() { + return this.amount; + } + public void setAmount(Int64 value) { + this.amount = value; + } + private Price price; + public Price getPrice() { + return this.price; + } + public void setPrice(Price value) { + this.price = value; + } + private Uint32 flags; + public Uint32 getFlags() { + return this.flags; + } + public void setFlags(Uint32 value) { + this.flags = value; + } + private OfferEntryExt ext; + public OfferEntryExt getExt() { + return this.ext; + } + public void setExt(OfferEntryExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, OfferEntry encodedOfferEntry) throws IOException{ + AccountID.encode(stream, encodedOfferEntry.sellerID); + Uint64.encode(stream, encodedOfferEntry.offerID); + Asset.encode(stream, encodedOfferEntry.selling); + Asset.encode(stream, encodedOfferEntry.buying); + Int64.encode(stream, encodedOfferEntry.amount); + Price.encode(stream, encodedOfferEntry.price); + Uint32.encode(stream, encodedOfferEntry.flags); + OfferEntryExt.encode(stream, encodedOfferEntry.ext); + } + public static OfferEntry decode(XdrDataInputStream stream) throws IOException { + OfferEntry decodedOfferEntry = new OfferEntry(); + decodedOfferEntry.sellerID = AccountID.decode(stream); + decodedOfferEntry.offerID = Uint64.decode(stream); + decodedOfferEntry.selling = Asset.decode(stream); + decodedOfferEntry.buying = Asset.decode(stream); + decodedOfferEntry.amount = Int64.decode(stream); + decodedOfferEntry.price = Price.decode(stream); + decodedOfferEntry.flags = Uint32.decode(stream); + decodedOfferEntry.ext = OfferEntryExt.decode(stream); + return decodedOfferEntry; + } + + public static class OfferEntryExt { + public OfferEntryExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, OfferEntryExt encodedOfferEntryExt) throws IOException { + stream.writeInt(encodedOfferEntryExt.getDiscriminant().intValue()); + switch (encodedOfferEntryExt.getDiscriminant()) { + case 0: + break; + } + } + public static OfferEntryExt decode(XdrDataInputStream stream) throws IOException { + OfferEntryExt decodedOfferEntryExt = new OfferEntryExt(); + Integer discriminant = stream.readInt(); + decodedOfferEntryExt.setDiscriminant(discriminant); + switch (decodedOfferEntryExt.getDiscriminant()) { + case 0: + break; + } + return decodedOfferEntryExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/OfferEntryFlags.java b/app/src/main/java/org/stellar/sdk/xdr/OfferEntryFlags.java new file mode 100644 index 0000000000..2dfc110fd4 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/OfferEntryFlags.java @@ -0,0 +1,43 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum OfferEntryFlags +// { +// // issuer has authorized account to perform transactions with its credit +// PASSIVE_FLAG = 1 +// }; + +// =========================================================================== +public enum OfferEntryFlags { + PASSIVE_FLAG(1), + ; + private int mValue; + + OfferEntryFlags(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static OfferEntryFlags decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 1: return PASSIVE_FLAG; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, OfferEntryFlags value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Operation.java b/app/src/main/java/org/stellar/sdk/xdr/Operation.java new file mode 100644 index 0000000000..5b85812976 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Operation.java @@ -0,0 +1,255 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Operation +// { +// // sourceAccount is the account used to run the operation +// // if not set, the runtime defaults to "sourceAccount" specified at +// // the transaction level +// AccountID* sourceAccount; +// +// union switch (OperationType type) +// { +// case CREATE_ACCOUNT: +// CreateAccountOp createAccountOp; +// case PAYMENT: +// PaymentOp paymentOp; +// case PATH_PAYMENT: +// PathPaymentOp pathPaymentOp; +// case MANAGE_OFFER: +// ManageOfferOp manageOfferOp; +// case CREATE_PASSIVE_OFFER: +// CreatePassiveOfferOp createPassiveOfferOp; +// case SET_OPTIONS: +// SetOptionsOp setOptionsOp; +// case CHANGE_TRUST: +// ChangeTrustOp changeTrustOp; +// case ALLOW_TRUST: +// AllowTrustOp allowTrustOp; +// case ACCOUNT_MERGE: +// AccountID destination; +// case INFLATION: +// void; +// case MANAGE_DATA: +// ManageDataOp manageDataOp; +// case BUMP_SEQUENCE: +// BumpSequenceOp bumpSequenceOp; +// } +// body; +// }; + +// =========================================================================== +public class Operation { + public Operation () {} + private AccountID sourceAccount; + public AccountID getSourceAccount() { + return this.sourceAccount; + } + public void setSourceAccount(AccountID value) { + this.sourceAccount = value; + } + private OperationBody body; + public OperationBody getBody() { + return this.body; + } + public void setBody(OperationBody value) { + this.body = value; + } + public static void encode(XdrDataOutputStream stream, Operation encodedOperation) throws IOException{ + if (encodedOperation.sourceAccount != null) { + stream.writeInt(1); + AccountID.encode(stream, encodedOperation.sourceAccount); + } else { + stream.writeInt(0); + } + OperationBody.encode(stream, encodedOperation.body); + } + public static Operation decode(XdrDataInputStream stream) throws IOException { + Operation decodedOperation = new Operation(); + int sourceAccountPresent = stream.readInt(); + if (sourceAccountPresent != 0) { + decodedOperation.sourceAccount = AccountID.decode(stream); + } + decodedOperation.body = OperationBody.decode(stream); + return decodedOperation; + } + + public static class OperationBody { + public OperationBody () {} + OperationType type; + public OperationType getDiscriminant() { + return this.type; + } + public void setDiscriminant(OperationType value) { + this.type = value; + } + private CreateAccountOp createAccountOp; + public CreateAccountOp getCreateAccountOp() { + return this.createAccountOp; + } + public void setCreateAccountOp(CreateAccountOp value) { + this.createAccountOp = value; + } + private PaymentOp paymentOp; + public PaymentOp getPaymentOp() { + return this.paymentOp; + } + public void setPaymentOp(PaymentOp value) { + this.paymentOp = value; + } + private PathPaymentOp pathPaymentOp; + public PathPaymentOp getPathPaymentOp() { + return this.pathPaymentOp; + } + public void setPathPaymentOp(PathPaymentOp value) { + this.pathPaymentOp = value; + } + private ManageOfferOp manageOfferOp; + public ManageOfferOp getManageOfferOp() { + return this.manageOfferOp; + } + public void setManageOfferOp(ManageOfferOp value) { + this.manageOfferOp = value; + } + private CreatePassiveOfferOp createPassiveOfferOp; + public CreatePassiveOfferOp getCreatePassiveOfferOp() { + return this.createPassiveOfferOp; + } + public void setCreatePassiveOfferOp(CreatePassiveOfferOp value) { + this.createPassiveOfferOp = value; + } + private SetOptionsOp setOptionsOp; + public SetOptionsOp getSetOptionsOp() { + return this.setOptionsOp; + } + public void setSetOptionsOp(SetOptionsOp value) { + this.setOptionsOp = value; + } + private ChangeTrustOp changeTrustOp; + public ChangeTrustOp getChangeTrustOp() { + return this.changeTrustOp; + } + public void setChangeTrustOp(ChangeTrustOp value) { + this.changeTrustOp = value; + } + private AllowTrustOp allowTrustOp; + public AllowTrustOp getAllowTrustOp() { + return this.allowTrustOp; + } + public void setAllowTrustOp(AllowTrustOp value) { + this.allowTrustOp = value; + } + private AccountID destination; + public AccountID getDestination() { + return this.destination; + } + public void setDestination(AccountID value) { + this.destination = value; + } + private ManageDataOp manageDataOp; + public ManageDataOp getManageDataOp() { + return this.manageDataOp; + } + public void setManageDataOp(ManageDataOp value) { + this.manageDataOp = value; + } + private BumpSequenceOp bumpSequenceOp; + public BumpSequenceOp getBumpSequenceOp() { + return this.bumpSequenceOp; + } + public void setBumpSequenceOp(BumpSequenceOp value) { + this.bumpSequenceOp = value; + } + public static void encode(XdrDataOutputStream stream, OperationBody encodedOperationBody) throws IOException { + stream.writeInt(encodedOperationBody.getDiscriminant().getValue()); + switch (encodedOperationBody.getDiscriminant()) { + case CREATE_ACCOUNT: + CreateAccountOp.encode(stream, encodedOperationBody.createAccountOp); + break; + case PAYMENT: + PaymentOp.encode(stream, encodedOperationBody.paymentOp); + break; + case PATH_PAYMENT: + PathPaymentOp.encode(stream, encodedOperationBody.pathPaymentOp); + break; + case MANAGE_OFFER: + ManageOfferOp.encode(stream, encodedOperationBody.manageOfferOp); + break; + case CREATE_PASSIVE_OFFER: + CreatePassiveOfferOp.encode(stream, encodedOperationBody.createPassiveOfferOp); + break; + case SET_OPTIONS: + SetOptionsOp.encode(stream, encodedOperationBody.setOptionsOp); + break; + case CHANGE_TRUST: + ChangeTrustOp.encode(stream, encodedOperationBody.changeTrustOp); + break; + case ALLOW_TRUST: + AllowTrustOp.encode(stream, encodedOperationBody.allowTrustOp); + break; + case ACCOUNT_MERGE: + AccountID.encode(stream, encodedOperationBody.destination); + break; + case INFLATION: + break; + case MANAGE_DATA: + ManageDataOp.encode(stream, encodedOperationBody.manageDataOp); + break; + case BUMP_SEQUENCE: + BumpSequenceOp.encode(stream, encodedOperationBody.bumpSequenceOp); + break; + } + } + public static OperationBody decode(XdrDataInputStream stream) throws IOException { + OperationBody decodedOperationBody = new OperationBody(); + OperationType discriminant = OperationType.decode(stream); + decodedOperationBody.setDiscriminant(discriminant); + switch (decodedOperationBody.getDiscriminant()) { + case CREATE_ACCOUNT: + decodedOperationBody.createAccountOp = CreateAccountOp.decode(stream); + break; + case PAYMENT: + decodedOperationBody.paymentOp = PaymentOp.decode(stream); + break; + case PATH_PAYMENT: + decodedOperationBody.pathPaymentOp = PathPaymentOp.decode(stream); + break; + case MANAGE_OFFER: + decodedOperationBody.manageOfferOp = ManageOfferOp.decode(stream); + break; + case CREATE_PASSIVE_OFFER: + decodedOperationBody.createPassiveOfferOp = CreatePassiveOfferOp.decode(stream); + break; + case SET_OPTIONS: + decodedOperationBody.setOptionsOp = SetOptionsOp.decode(stream); + break; + case CHANGE_TRUST: + decodedOperationBody.changeTrustOp = ChangeTrustOp.decode(stream); + break; + case ALLOW_TRUST: + decodedOperationBody.allowTrustOp = AllowTrustOp.decode(stream); + break; + case ACCOUNT_MERGE: + decodedOperationBody.destination = AccountID.decode(stream); + break; + case INFLATION: + break; + case MANAGE_DATA: + decodedOperationBody.manageDataOp = ManageDataOp.decode(stream); + break; + case BUMP_SEQUENCE: + decodedOperationBody.bumpSequenceOp = BumpSequenceOp.decode(stream); + break; + } + return decodedOperationBody; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/OperationMeta.java b/app/src/main/java/org/stellar/sdk/xdr/OperationMeta.java new file mode 100644 index 0000000000..d57e9f3b0d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/OperationMeta.java @@ -0,0 +1,34 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct OperationMeta +// { +// LedgerEntryChanges changes; +// }; + +// =========================================================================== +public class OperationMeta { + public OperationMeta () {} + private LedgerEntryChanges changes; + public LedgerEntryChanges getChanges() { + return this.changes; + } + public void setChanges(LedgerEntryChanges value) { + this.changes = value; + } + public static void encode(XdrDataOutputStream stream, OperationMeta encodedOperationMeta) throws IOException{ + LedgerEntryChanges.encode(stream, encodedOperationMeta.changes); + } + public static OperationMeta decode(XdrDataInputStream stream) throws IOException { + OperationMeta decodedOperationMeta = new OperationMeta(); + decodedOperationMeta.changes = LedgerEntryChanges.decode(stream); + return decodedOperationMeta; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/OperationResult.java b/app/src/main/java/org/stellar/sdk/xdr/OperationResult.java new file mode 100644 index 0000000000..aaeb8f194c --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/OperationResult.java @@ -0,0 +1,267 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union OperationResult switch (OperationResultCode code) +// { +// case opINNER: +// union switch (OperationType type) +// { +// case CREATE_ACCOUNT: +// CreateAccountResult createAccountResult; +// case PAYMENT: +// PaymentResult paymentResult; +// case PATH_PAYMENT: +// PathPaymentResult pathPaymentResult; +// case MANAGE_OFFER: +// ManageOfferResult manageOfferResult; +// case CREATE_PASSIVE_OFFER: +// ManageOfferResult createPassiveOfferResult; +// case SET_OPTIONS: +// SetOptionsResult setOptionsResult; +// case CHANGE_TRUST: +// ChangeTrustResult changeTrustResult; +// case ALLOW_TRUST: +// AllowTrustResult allowTrustResult; +// case ACCOUNT_MERGE: +// AccountMergeResult accountMergeResult; +// case INFLATION: +// InflationResult inflationResult; +// case MANAGE_DATA: +// ManageDataResult manageDataResult; +// case BUMP_SEQUENCE: +// BumpSequenceResult bumpSeqResult; +// } +// tr; +// default: +// void; +// }; + +// =========================================================================== +public class OperationResult { + public OperationResult () {} + OperationResultCode code; + public OperationResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(OperationResultCode value) { + this.code = value; + } + private OperationResultTr tr; + public OperationResultTr getTr() { + return this.tr; + } + public void setTr(OperationResultTr value) { + this.tr = value; + } + public static void encode(XdrDataOutputStream stream, OperationResult encodedOperationResult) throws IOException { + stream.writeInt(encodedOperationResult.getDiscriminant().getValue()); + switch (encodedOperationResult.getDiscriminant()) { + case opINNER: + OperationResultTr.encode(stream, encodedOperationResult.tr); + break; + default: + break; + } + } + public static OperationResult decode(XdrDataInputStream stream) throws IOException { + OperationResult decodedOperationResult = new OperationResult(); + OperationResultCode discriminant = OperationResultCode.decode(stream); + decodedOperationResult.setDiscriminant(discriminant); + switch (decodedOperationResult.getDiscriminant()) { + case opINNER: + decodedOperationResult.tr = OperationResultTr.decode(stream); + break; + default: + break; + } + return decodedOperationResult; + } + + public static class OperationResultTr { + public OperationResultTr () {} + OperationType type; + public OperationType getDiscriminant() { + return this.type; + } + public void setDiscriminant(OperationType value) { + this.type = value; + } + private CreateAccountResult createAccountResult; + public CreateAccountResult getCreateAccountResult() { + return this.createAccountResult; + } + public void setCreateAccountResult(CreateAccountResult value) { + this.createAccountResult = value; + } + private PaymentResult paymentResult; + public PaymentResult getPaymentResult() { + return this.paymentResult; + } + public void setPaymentResult(PaymentResult value) { + this.paymentResult = value; + } + private PathPaymentResult pathPaymentResult; + public PathPaymentResult getPathPaymentResult() { + return this.pathPaymentResult; + } + public void setPathPaymentResult(PathPaymentResult value) { + this.pathPaymentResult = value; + } + private ManageOfferResult manageOfferResult; + public ManageOfferResult getManageOfferResult() { + return this.manageOfferResult; + } + public void setManageOfferResult(ManageOfferResult value) { + this.manageOfferResult = value; + } + private ManageOfferResult createPassiveOfferResult; + public ManageOfferResult getCreatePassiveOfferResult() { + return this.createPassiveOfferResult; + } + public void setCreatePassiveOfferResult(ManageOfferResult value) { + this.createPassiveOfferResult = value; + } + private SetOptionsResult setOptionsResult; + public SetOptionsResult getSetOptionsResult() { + return this.setOptionsResult; + } + public void setSetOptionsResult(SetOptionsResult value) { + this.setOptionsResult = value; + } + private ChangeTrustResult changeTrustResult; + public ChangeTrustResult getChangeTrustResult() { + return this.changeTrustResult; + } + public void setChangeTrustResult(ChangeTrustResult value) { + this.changeTrustResult = value; + } + private AllowTrustResult allowTrustResult; + public AllowTrustResult getAllowTrustResult() { + return this.allowTrustResult; + } + public void setAllowTrustResult(AllowTrustResult value) { + this.allowTrustResult = value; + } + private AccountMergeResult accountMergeResult; + public AccountMergeResult getAccountMergeResult() { + return this.accountMergeResult; + } + public void setAccountMergeResult(AccountMergeResult value) { + this.accountMergeResult = value; + } + private InflationResult inflationResult; + public InflationResult getInflationResult() { + return this.inflationResult; + } + public void setInflationResult(InflationResult value) { + this.inflationResult = value; + } + private ManageDataResult manageDataResult; + public ManageDataResult getManageDataResult() { + return this.manageDataResult; + } + public void setManageDataResult(ManageDataResult value) { + this.manageDataResult = value; + } + private BumpSequenceResult bumpSeqResult; + public BumpSequenceResult getBumpSeqResult() { + return this.bumpSeqResult; + } + public void setBumpSeqResult(BumpSequenceResult value) { + this.bumpSeqResult = value; + } + public static void encode(XdrDataOutputStream stream, OperationResultTr encodedOperationResultTr) throws IOException { + stream.writeInt(encodedOperationResultTr.getDiscriminant().getValue()); + switch (encodedOperationResultTr.getDiscriminant()) { + case CREATE_ACCOUNT: + CreateAccountResult.encode(stream, encodedOperationResultTr.createAccountResult); + break; + case PAYMENT: + PaymentResult.encode(stream, encodedOperationResultTr.paymentResult); + break; + case PATH_PAYMENT: + PathPaymentResult.encode(stream, encodedOperationResultTr.pathPaymentResult); + break; + case MANAGE_OFFER: + ManageOfferResult.encode(stream, encodedOperationResultTr.manageOfferResult); + break; + case CREATE_PASSIVE_OFFER: + ManageOfferResult.encode(stream, encodedOperationResultTr.createPassiveOfferResult); + break; + case SET_OPTIONS: + SetOptionsResult.encode(stream, encodedOperationResultTr.setOptionsResult); + break; + case CHANGE_TRUST: + ChangeTrustResult.encode(stream, encodedOperationResultTr.changeTrustResult); + break; + case ALLOW_TRUST: + AllowTrustResult.encode(stream, encodedOperationResultTr.allowTrustResult); + break; + case ACCOUNT_MERGE: + AccountMergeResult.encode(stream, encodedOperationResultTr.accountMergeResult); + break; + case INFLATION: + InflationResult.encode(stream, encodedOperationResultTr.inflationResult); + break; + case MANAGE_DATA: + ManageDataResult.encode(stream, encodedOperationResultTr.manageDataResult); + break; + case BUMP_SEQUENCE: + BumpSequenceResult.encode(stream, encodedOperationResultTr.bumpSeqResult); + break; + } + } + public static OperationResultTr decode(XdrDataInputStream stream) throws IOException { + OperationResultTr decodedOperationResultTr = new OperationResultTr(); + OperationType discriminant = OperationType.decode(stream); + decodedOperationResultTr.setDiscriminant(discriminant); + switch (decodedOperationResultTr.getDiscriminant()) { + case CREATE_ACCOUNT: + decodedOperationResultTr.createAccountResult = CreateAccountResult.decode(stream); + break; + case PAYMENT: + decodedOperationResultTr.paymentResult = PaymentResult.decode(stream); + break; + case PATH_PAYMENT: + decodedOperationResultTr.pathPaymentResult = PathPaymentResult.decode(stream); + break; + case MANAGE_OFFER: + decodedOperationResultTr.manageOfferResult = ManageOfferResult.decode(stream); + break; + case CREATE_PASSIVE_OFFER: + decodedOperationResultTr.createPassiveOfferResult = ManageOfferResult.decode(stream); + break; + case SET_OPTIONS: + decodedOperationResultTr.setOptionsResult = SetOptionsResult.decode(stream); + break; + case CHANGE_TRUST: + decodedOperationResultTr.changeTrustResult = ChangeTrustResult.decode(stream); + break; + case ALLOW_TRUST: + decodedOperationResultTr.allowTrustResult = AllowTrustResult.decode(stream); + break; + case ACCOUNT_MERGE: + decodedOperationResultTr.accountMergeResult = AccountMergeResult.decode(stream); + break; + case INFLATION: + decodedOperationResultTr.inflationResult = InflationResult.decode(stream); + break; + case MANAGE_DATA: + decodedOperationResultTr.manageDataResult = ManageDataResult.decode(stream); + break; + case BUMP_SEQUENCE: + decodedOperationResultTr.bumpSeqResult = BumpSequenceResult.decode(stream); + break; + } + return decodedOperationResultTr; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/OperationResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/OperationResultCode.java new file mode 100644 index 0000000000..739420de02 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/OperationResultCode.java @@ -0,0 +1,52 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum OperationResultCode +// { +// opINNER = 0, // inner object result is valid +// +// opBAD_AUTH = -1, // too few valid signatures / wrong network +// opNO_ACCOUNT = -2, // source account was not found +// opNOT_SUPPORTED = -3 // operation not supported at this time +// }; + +// =========================================================================== +public enum OperationResultCode { + opINNER(0), + opBAD_AUTH(-1), + opNO_ACCOUNT(-2), + opNOT_SUPPORTED(-3), + ; + private int mValue; + + OperationResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static OperationResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return opINNER; + case -1: return opBAD_AUTH; + case -2: return opNO_ACCOUNT; + case -3: return opNOT_SUPPORTED; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, OperationResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/OperationType.java b/app/src/main/java/org/stellar/sdk/xdr/OperationType.java new file mode 100644 index 0000000000..bfb05f5494 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/OperationType.java @@ -0,0 +1,75 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum OperationType +// { +// CREATE_ACCOUNT = 0, +// PAYMENT = 1, +// PATH_PAYMENT = 2, +// MANAGE_OFFER = 3, +// CREATE_PASSIVE_OFFER = 4, +// SET_OPTIONS = 5, +// CHANGE_TRUST = 6, +// ALLOW_TRUST = 7, +// ACCOUNT_MERGE = 8, +// INFLATION = 9, +// MANAGE_DATA = 10, +// BUMP_SEQUENCE = 11 +// }; + +// =========================================================================== +public enum OperationType { + CREATE_ACCOUNT(0), + PAYMENT(1), + PATH_PAYMENT(2), + MANAGE_OFFER(3), + CREATE_PASSIVE_OFFER(4), + SET_OPTIONS(5), + CHANGE_TRUST(6), + ALLOW_TRUST(7), + ACCOUNT_MERGE(8), + INFLATION(9), + MANAGE_DATA(10), + BUMP_SEQUENCE(11), + ; + private int mValue; + + OperationType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static OperationType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return CREATE_ACCOUNT; + case 1: return PAYMENT; + case 2: return PATH_PAYMENT; + case 3: return MANAGE_OFFER; + case 4: return CREATE_PASSIVE_OFFER; + case 5: return SET_OPTIONS; + case 6: return CHANGE_TRUST; + case 7: return ALLOW_TRUST; + case 8: return ACCOUNT_MERGE; + case 9: return INFLATION; + case 10: return MANAGE_DATA; + case 11: return BUMP_SEQUENCE; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, OperationType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PathPaymentOp.java b/app/src/main/java/org/stellar/sdk/xdr/PathPaymentOp.java new file mode 100644 index 0000000000..4cf44b5e90 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PathPaymentOp.java @@ -0,0 +1,96 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct PathPaymentOp +// { +// Asset sendAsset; // asset we pay with +// int64 sendMax; // the maximum amount of sendAsset to +// // send (excluding fees). +// // The operation will fail if can't be met +// +// AccountID destination; // recipient of the payment +// Asset destAsset; // what they end up with +// int64 destAmount; // amount they end up with +// +// Asset path<5>; // additional hops it must go through to get there +// }; + +// =========================================================================== +public class PathPaymentOp { + public PathPaymentOp () {} + private Asset sendAsset; + public Asset getSendAsset() { + return this.sendAsset; + } + public void setSendAsset(Asset value) { + this.sendAsset = value; + } + private Int64 sendMax; + public Int64 getSendMax() { + return this.sendMax; + } + public void setSendMax(Int64 value) { + this.sendMax = value; + } + private AccountID destination; + public AccountID getDestination() { + return this.destination; + } + public void setDestination(AccountID value) { + this.destination = value; + } + private Asset destAsset; + public Asset getDestAsset() { + return this.destAsset; + } + public void setDestAsset(Asset value) { + this.destAsset = value; + } + private Int64 destAmount; + public Int64 getDestAmount() { + return this.destAmount; + } + public void setDestAmount(Int64 value) { + this.destAmount = value; + } + private Asset[] path; + public Asset[] getPath() { + return this.path; + } + public void setPath(Asset[] value) { + this.path = value; + } + public static void encode(XdrDataOutputStream stream, PathPaymentOp encodedPathPaymentOp) throws IOException{ + Asset.encode(stream, encodedPathPaymentOp.sendAsset); + Int64.encode(stream, encodedPathPaymentOp.sendMax); + AccountID.encode(stream, encodedPathPaymentOp.destination); + Asset.encode(stream, encodedPathPaymentOp.destAsset); + Int64.encode(stream, encodedPathPaymentOp.destAmount); + int pathsize = encodedPathPaymentOp.getPath().length; + stream.writeInt(pathsize); + for (int i = 0; i < pathsize; i++) { + Asset.encode(stream, encodedPathPaymentOp.path[i]); + } + } + public static PathPaymentOp decode(XdrDataInputStream stream) throws IOException { + PathPaymentOp decodedPathPaymentOp = new PathPaymentOp(); + decodedPathPaymentOp.sendAsset = Asset.decode(stream); + decodedPathPaymentOp.sendMax = Int64.decode(stream); + decodedPathPaymentOp.destination = AccountID.decode(stream); + decodedPathPaymentOp.destAsset = Asset.decode(stream); + decodedPathPaymentOp.destAmount = Int64.decode(stream); + int pathsize = stream.readInt(); + decodedPathPaymentOp.path = new Asset[pathsize]; + for (int i = 0; i < pathsize; i++) { + decodedPathPaymentOp.path[i] = Asset.decode(stream); + } + return decodedPathPaymentOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PathPaymentResult.java b/app/src/main/java/org/stellar/sdk/xdr/PathPaymentResult.java new file mode 100644 index 0000000000..6ca7c8f373 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PathPaymentResult.java @@ -0,0 +1,115 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union PathPaymentResult switch (PathPaymentResultCode code) +// { +// case PATH_PAYMENT_SUCCESS: +// struct +// { +// ClaimOfferAtom offers<>; +// SimplePaymentResult last; +// } success; +// case PATH_PAYMENT_NO_ISSUER: +// Asset noIssuer; // the asset that caused the error +// default: +// void; +// }; + +// =========================================================================== +public class PathPaymentResult { + public PathPaymentResult () {} + PathPaymentResultCode code; + public PathPaymentResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(PathPaymentResultCode value) { + this.code = value; + } + private PathPaymentResultSuccess success; + public PathPaymentResultSuccess getSuccess() { + return this.success; + } + public void setSuccess(PathPaymentResultSuccess value) { + this.success = value; + } + private Asset noIssuer; + public Asset getNoIssuer() { + return this.noIssuer; + } + public void setNoIssuer(Asset value) { + this.noIssuer = value; + } + public static void encode(XdrDataOutputStream stream, PathPaymentResult encodedPathPaymentResult) throws IOException { + stream.writeInt(encodedPathPaymentResult.getDiscriminant().getValue()); + switch (encodedPathPaymentResult.getDiscriminant()) { + case PATH_PAYMENT_SUCCESS: + PathPaymentResultSuccess.encode(stream, encodedPathPaymentResult.success); + break; + case PATH_PAYMENT_NO_ISSUER: + Asset.encode(stream, encodedPathPaymentResult.noIssuer); + break; + default: + break; + } + } + public static PathPaymentResult decode(XdrDataInputStream stream) throws IOException { + PathPaymentResult decodedPathPaymentResult = new PathPaymentResult(); + PathPaymentResultCode discriminant = PathPaymentResultCode.decode(stream); + decodedPathPaymentResult.setDiscriminant(discriminant); + switch (decodedPathPaymentResult.getDiscriminant()) { + case PATH_PAYMENT_SUCCESS: + decodedPathPaymentResult.success = PathPaymentResultSuccess.decode(stream); + break; + case PATH_PAYMENT_NO_ISSUER: + decodedPathPaymentResult.noIssuer = Asset.decode(stream); + break; + default: + break; + } + return decodedPathPaymentResult; + } + + public static class PathPaymentResultSuccess { + public PathPaymentResultSuccess () {} + private ClaimOfferAtom[] offers; + public ClaimOfferAtom[] getOffers() { + return this.offers; + } + public void setOffers(ClaimOfferAtom[] value) { + this.offers = value; + } + private SimplePaymentResult last; + public SimplePaymentResult getLast() { + return this.last; + } + public void setLast(SimplePaymentResult value) { + this.last = value; + } + public static void encode(XdrDataOutputStream stream, PathPaymentResultSuccess encodedPathPaymentResultSuccess) throws IOException{ + int offerssize = encodedPathPaymentResultSuccess.getOffers().length; + stream.writeInt(offerssize); + for (int i = 0; i < offerssize; i++) { + ClaimOfferAtom.encode(stream, encodedPathPaymentResultSuccess.offers[i]); + } + SimplePaymentResult.encode(stream, encodedPathPaymentResultSuccess.last); + } + public static PathPaymentResultSuccess decode(XdrDataInputStream stream) throws IOException { + PathPaymentResultSuccess decodedPathPaymentResultSuccess = new PathPaymentResultSuccess(); + int offerssize = stream.readInt(); + decodedPathPaymentResultSuccess.offers = new ClaimOfferAtom[offerssize]; + for (int i = 0; i < offerssize; i++) { + decodedPathPaymentResultSuccess.offers[i] = ClaimOfferAtom.decode(stream); + } + decodedPathPaymentResultSuccess.last = SimplePaymentResult.decode(stream); + return decodedPathPaymentResultSuccess; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PathPaymentResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/PathPaymentResultCode.java new file mode 100644 index 0000000000..026297001c --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PathPaymentResultCode.java @@ -0,0 +1,81 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum PathPaymentResultCode +// { +// // codes considered as "success" for the operation +// PATH_PAYMENT_SUCCESS = 0, // success +// +// // codes considered as "failure" for the operation +// PATH_PAYMENT_MALFORMED = -1, // bad input +// PATH_PAYMENT_UNDERFUNDED = -2, // not enough funds in source account +// PATH_PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account +// PATH_PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer +// PATH_PAYMENT_NO_DESTINATION = -5, // destination account does not exist +// PATH_PAYMENT_NO_TRUST = -6, // dest missing a trust line for asset +// PATH_PAYMENT_NOT_AUTHORIZED = -7, // dest not authorized to hold asset +// PATH_PAYMENT_LINE_FULL = -8, // dest would go above their limit +// PATH_PAYMENT_NO_ISSUER = -9, // missing issuer on one asset +// PATH_PAYMENT_TOO_FEW_OFFERS = -10, // not enough offers to satisfy path +// PATH_PAYMENT_OFFER_CROSS_SELF = -11, // would cross one of its own offers +// PATH_PAYMENT_OVER_SENDMAX = -12 // could not satisfy sendmax +// }; + +// =========================================================================== +public enum PathPaymentResultCode { + PATH_PAYMENT_SUCCESS(0), + PATH_PAYMENT_MALFORMED(-1), + PATH_PAYMENT_UNDERFUNDED(-2), + PATH_PAYMENT_SRC_NO_TRUST(-3), + PATH_PAYMENT_SRC_NOT_AUTHORIZED(-4), + PATH_PAYMENT_NO_DESTINATION(-5), + PATH_PAYMENT_NO_TRUST(-6), + PATH_PAYMENT_NOT_AUTHORIZED(-7), + PATH_PAYMENT_LINE_FULL(-8), + PATH_PAYMENT_NO_ISSUER(-9), + PATH_PAYMENT_TOO_FEW_OFFERS(-10), + PATH_PAYMENT_OFFER_CROSS_SELF(-11), + PATH_PAYMENT_OVER_SENDMAX(-12), + ; + private int mValue; + + PathPaymentResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static PathPaymentResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return PATH_PAYMENT_SUCCESS; + case -1: return PATH_PAYMENT_MALFORMED; + case -2: return PATH_PAYMENT_UNDERFUNDED; + case -3: return PATH_PAYMENT_SRC_NO_TRUST; + case -4: return PATH_PAYMENT_SRC_NOT_AUTHORIZED; + case -5: return PATH_PAYMENT_NO_DESTINATION; + case -6: return PATH_PAYMENT_NO_TRUST; + case -7: return PATH_PAYMENT_NOT_AUTHORIZED; + case -8: return PATH_PAYMENT_LINE_FULL; + case -9: return PATH_PAYMENT_NO_ISSUER; + case -10: return PATH_PAYMENT_TOO_FEW_OFFERS; + case -11: return PATH_PAYMENT_OFFER_CROSS_SELF; + case -12: return PATH_PAYMENT_OVER_SENDMAX; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, PathPaymentResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PaymentOp.java b/app/src/main/java/org/stellar/sdk/xdr/PaymentOp.java new file mode 100644 index 0000000000..93266dbfe9 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PaymentOp.java @@ -0,0 +1,54 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct PaymentOp +// { +// AccountID destination; // recipient of the payment +// Asset asset; // what they end up with +// int64 amount; // amount they end up with +// }; + +// =========================================================================== +public class PaymentOp { + public PaymentOp () {} + private AccountID destination; + public AccountID getDestination() { + return this.destination; + } + public void setDestination(AccountID value) { + this.destination = value; + } + private Asset asset; + public Asset getAsset() { + return this.asset; + } + public void setAsset(Asset value) { + this.asset = value; + } + private Int64 amount; + public Int64 getAmount() { + return this.amount; + } + public void setAmount(Int64 value) { + this.amount = value; + } + public static void encode(XdrDataOutputStream stream, PaymentOp encodedPaymentOp) throws IOException{ + AccountID.encode(stream, encodedPaymentOp.destination); + Asset.encode(stream, encodedPaymentOp.asset); + Int64.encode(stream, encodedPaymentOp.amount); + } + public static PaymentOp decode(XdrDataInputStream stream) throws IOException { + PaymentOp decodedPaymentOp = new PaymentOp(); + decodedPaymentOp.destination = AccountID.decode(stream); + decodedPaymentOp.asset = Asset.decode(stream); + decodedPaymentOp.amount = Int64.decode(stream); + return decodedPaymentOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PaymentResult.java b/app/src/main/java/org/stellar/sdk/xdr/PaymentResult.java new file mode 100644 index 0000000000..04e9f9d5a3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PaymentResult.java @@ -0,0 +1,50 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union PaymentResult switch (PaymentResultCode code) +// { +// case PAYMENT_SUCCESS: +// void; +// default: +// void; +// }; + +// =========================================================================== +public class PaymentResult { + public PaymentResult () {} + PaymentResultCode code; + public PaymentResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(PaymentResultCode value) { + this.code = value; + } + public static void encode(XdrDataOutputStream stream, PaymentResult encodedPaymentResult) throws IOException { + stream.writeInt(encodedPaymentResult.getDiscriminant().getValue()); + switch (encodedPaymentResult.getDiscriminant()) { + case PAYMENT_SUCCESS: + break; + default: + break; + } + } + public static PaymentResult decode(XdrDataInputStream stream) throws IOException { + PaymentResult decodedPaymentResult = new PaymentResult(); + PaymentResultCode discriminant = PaymentResultCode.decode(stream); + decodedPaymentResult.setDiscriminant(discriminant); + switch (decodedPaymentResult.getDiscriminant()) { + case PAYMENT_SUCCESS: + break; + default: + break; + } + return decodedPaymentResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PaymentResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/PaymentResultCode.java new file mode 100644 index 0000000000..4bff90f295 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PaymentResultCode.java @@ -0,0 +1,72 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum PaymentResultCode +// { +// // codes considered as "success" for the operation +// PAYMENT_SUCCESS = 0, // payment successfuly completed +// +// // codes considered as "failure" for the operation +// PAYMENT_MALFORMED = -1, // bad input +// PAYMENT_UNDERFUNDED = -2, // not enough funds in source account +// PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account +// PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer +// PAYMENT_NO_DESTINATION = -5, // destination account does not exist +// PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset +// PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset +// PAYMENT_LINE_FULL = -8, // destination would go above their limit +// PAYMENT_NO_ISSUER = -9 // missing issuer on asset +// }; + +// =========================================================================== +public enum PaymentResultCode { + PAYMENT_SUCCESS(0), + PAYMENT_MALFORMED(-1), + PAYMENT_UNDERFUNDED(-2), + PAYMENT_SRC_NO_TRUST(-3), + PAYMENT_SRC_NOT_AUTHORIZED(-4), + PAYMENT_NO_DESTINATION(-5), + PAYMENT_NO_TRUST(-6), + PAYMENT_NOT_AUTHORIZED(-7), + PAYMENT_LINE_FULL(-8), + PAYMENT_NO_ISSUER(-9), + ; + private int mValue; + + PaymentResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static PaymentResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return PAYMENT_SUCCESS; + case -1: return PAYMENT_MALFORMED; + case -2: return PAYMENT_UNDERFUNDED; + case -3: return PAYMENT_SRC_NO_TRUST; + case -4: return PAYMENT_SRC_NOT_AUTHORIZED; + case -5: return PAYMENT_NO_DESTINATION; + case -6: return PAYMENT_NO_TRUST; + case -7: return PAYMENT_NOT_AUTHORIZED; + case -8: return PAYMENT_LINE_FULL; + case -9: return PAYMENT_NO_ISSUER; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, PaymentResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PeerAddress.java b/app/src/main/java/org/stellar/sdk/xdr/PeerAddress.java new file mode 100644 index 0000000000..5ff26dbca9 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PeerAddress.java @@ -0,0 +1,118 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct PeerAddress +// { +// union switch (IPAddrType type) +// { +// case IPv4: +// opaque ipv4[4]; +// case IPv6: +// opaque ipv6[16]; +// } +// ip; +// uint32 port; +// uint32 numFailures; +// }; + +// =========================================================================== +public class PeerAddress { + public PeerAddress () {} + private PeerAddressIp ip; + public PeerAddressIp getIp() { + return this.ip; + } + public void setIp(PeerAddressIp value) { + this.ip = value; + } + private Uint32 port; + public Uint32 getPort() { + return this.port; + } + public void setPort(Uint32 value) { + this.port = value; + } + private Uint32 numFailures; + public Uint32 getNumFailures() { + return this.numFailures; + } + public void setNumFailures(Uint32 value) { + this.numFailures = value; + } + public static void encode(XdrDataOutputStream stream, PeerAddress encodedPeerAddress) throws IOException{ + PeerAddressIp.encode(stream, encodedPeerAddress.ip); + Uint32.encode(stream, encodedPeerAddress.port); + Uint32.encode(stream, encodedPeerAddress.numFailures); + } + public static PeerAddress decode(XdrDataInputStream stream) throws IOException { + PeerAddress decodedPeerAddress = new PeerAddress(); + decodedPeerAddress.ip = PeerAddressIp.decode(stream); + decodedPeerAddress.port = Uint32.decode(stream); + decodedPeerAddress.numFailures = Uint32.decode(stream); + return decodedPeerAddress; + } + + public static class PeerAddressIp { + public PeerAddressIp () {} + IPAddrType type; + public IPAddrType getDiscriminant() { + return this.type; + } + public void setDiscriminant(IPAddrType value) { + this.type = value; + } + private byte[] ipv4; + public byte[] getIpv4() { + return this.ipv4; + } + public void setIpv4(byte[] value) { + this.ipv4 = value; + } + private byte[] ipv6; + public byte[] getIpv6() { + return this.ipv6; + } + public void setIpv6(byte[] value) { + this.ipv6 = value; + } + public static void encode(XdrDataOutputStream stream, PeerAddressIp encodedPeerAddressIp) throws IOException { + stream.writeInt(encodedPeerAddressIp.getDiscriminant().getValue()); + switch (encodedPeerAddressIp.getDiscriminant()) { + case IPv4: + int ipv4size = encodedPeerAddressIp.ipv4.length; + stream.write(encodedPeerAddressIp.getIpv4(), 0, ipv4size); + break; + case IPv6: + int ipv6size = encodedPeerAddressIp.ipv6.length; + stream.write(encodedPeerAddressIp.getIpv6(), 0, ipv6size); + break; + } + } + public static PeerAddressIp decode(XdrDataInputStream stream) throws IOException { + PeerAddressIp decodedPeerAddressIp = new PeerAddressIp(); + IPAddrType discriminant = IPAddrType.decode(stream); + decodedPeerAddressIp.setDiscriminant(discriminant); + switch (decodedPeerAddressIp.getDiscriminant()) { + case IPv4: + int ipv4size = 4; + decodedPeerAddressIp.ipv4 = new byte[ipv4size]; + stream.read(decodedPeerAddressIp.ipv4, 0, ipv4size); + break; + case IPv6: + int ipv6size = 16; + decodedPeerAddressIp.ipv6 = new byte[ipv6size]; + stream.read(decodedPeerAddressIp.ipv6, 0, ipv6size); + break; + } + return decodedPeerAddressIp; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Price.java b/app/src/main/java/org/stellar/sdk/xdr/Price.java new file mode 100644 index 0000000000..7cd5581657 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Price.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Price +// { +// int32 n; // numerator +// int32 d; // denominator +// }; + +// =========================================================================== +public class Price { + public Price () {} + private Int32 n; + public Int32 getN() { + return this.n; + } + public void setN(Int32 value) { + this.n = value; + } + private Int32 d; + public Int32 getD() { + return this.d; + } + public void setD(Int32 value) { + this.d = value; + } + public static void encode(XdrDataOutputStream stream, Price encodedPrice) throws IOException{ + Int32.encode(stream, encodedPrice.n); + Int32.encode(stream, encodedPrice.d); + } + public static Price decode(XdrDataInputStream stream) throws IOException { + Price decodedPrice = new Price(); + decodedPrice.n = Int32.decode(stream); + decodedPrice.d = Int32.decode(stream); + return decodedPrice; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PublicKey.java b/app/src/main/java/org/stellar/sdk/xdr/PublicKey.java new file mode 100644 index 0000000000..746093fb5a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PublicKey.java @@ -0,0 +1,53 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union PublicKey switch (PublicKeyType type) +// { +// case PUBLIC_KEY_TYPE_ED25519: +// uint256 ed25519; +// }; + +// =========================================================================== +public class PublicKey { + public PublicKey () {} + PublicKeyType type; + public PublicKeyType getDiscriminant() { + return this.type; + } + public void setDiscriminant(PublicKeyType value) { + this.type = value; + } + private Uint256 ed25519; + public Uint256 getEd25519() { + return this.ed25519; + } + public void setEd25519(Uint256 value) { + this.ed25519 = value; + } + public static void encode(XdrDataOutputStream stream, PublicKey encodedPublicKey) throws IOException { + stream.writeInt(encodedPublicKey.getDiscriminant().getValue()); + switch (encodedPublicKey.getDiscriminant()) { + case PUBLIC_KEY_TYPE_ED25519: + Uint256.encode(stream, encodedPublicKey.ed25519); + break; + } + } + public static PublicKey decode(XdrDataInputStream stream) throws IOException { + PublicKey decodedPublicKey = new PublicKey(); + PublicKeyType discriminant = PublicKeyType.decode(stream); + decodedPublicKey.setDiscriminant(discriminant); + switch (decodedPublicKey.getDiscriminant()) { + case PUBLIC_KEY_TYPE_ED25519: + decodedPublicKey.ed25519 = Uint256.decode(stream); + break; + } + return decodedPublicKey; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/PublicKeyType.java b/app/src/main/java/org/stellar/sdk/xdr/PublicKeyType.java new file mode 100644 index 0000000000..1cfa0f0bd0 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/PublicKeyType.java @@ -0,0 +1,42 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum PublicKeyType +// { +// PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 +// }; + +// =========================================================================== +public enum PublicKeyType { + PUBLIC_KEY_TYPE_ED25519(0), + ; + private int mValue; + + PublicKeyType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static PublicKeyType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return PUBLIC_KEY_TYPE_ED25519; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, PublicKeyType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SCPBallot.java b/app/src/main/java/org/stellar/sdk/xdr/SCPBallot.java new file mode 100644 index 0000000000..2ab1face89 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SCPBallot.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct SCPBallot +// { +// uint32 counter; // n +// Value value; // x +// }; + +// =========================================================================== +public class SCPBallot { + public SCPBallot () {} + private Uint32 counter; + public Uint32 getCounter() { + return this.counter; + } + public void setCounter(Uint32 value) { + this.counter = value; + } + private Value value; + public Value getValue() { + return this.value; + } + public void setValue(Value value) { + this.value = value; + } + public static void encode(XdrDataOutputStream stream, SCPBallot encodedSCPBallot) throws IOException{ + Uint32.encode(stream, encodedSCPBallot.counter); + Value.encode(stream, encodedSCPBallot.value); + } + public static SCPBallot decode(XdrDataInputStream stream) throws IOException { + SCPBallot decodedSCPBallot = new SCPBallot(); + decodedSCPBallot.counter = Uint32.decode(stream); + decodedSCPBallot.value = Value.decode(stream); + return decodedSCPBallot; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SCPEnvelope.java b/app/src/main/java/org/stellar/sdk/xdr/SCPEnvelope.java new file mode 100644 index 0000000000..bedc991dc4 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SCPEnvelope.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct SCPEnvelope +// { +// SCPStatement statement; +// Signature signature; +// }; + +// =========================================================================== +public class SCPEnvelope { + public SCPEnvelope () {} + private SCPStatement statement; + public SCPStatement getStatement() { + return this.statement; + } + public void setStatement(SCPStatement value) { + this.statement = value; + } + private Signature signature; + public Signature getSignature() { + return this.signature; + } + public void setSignature(Signature value) { + this.signature = value; + } + public static void encode(XdrDataOutputStream stream, SCPEnvelope encodedSCPEnvelope) throws IOException{ + SCPStatement.encode(stream, encodedSCPEnvelope.statement); + Signature.encode(stream, encodedSCPEnvelope.signature); + } + public static SCPEnvelope decode(XdrDataInputStream stream) throws IOException { + SCPEnvelope decodedSCPEnvelope = new SCPEnvelope(); + decodedSCPEnvelope.statement = SCPStatement.decode(stream); + decodedSCPEnvelope.signature = Signature.decode(stream); + return decodedSCPEnvelope; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SCPHistoryEntry.java b/app/src/main/java/org/stellar/sdk/xdr/SCPHistoryEntry.java new file mode 100644 index 0000000000..2c8b9bc4b2 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SCPHistoryEntry.java @@ -0,0 +1,53 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union SCPHistoryEntry switch (int v) +// { +// case 0: +// SCPHistoryEntryV0 v0; +// }; + +// =========================================================================== +public class SCPHistoryEntry { + public SCPHistoryEntry () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + private SCPHistoryEntryV0 v0; + public SCPHistoryEntryV0 getV0() { + return this.v0; + } + public void setV0(SCPHistoryEntryV0 value) { + this.v0 = value; + } + public static void encode(XdrDataOutputStream stream, SCPHistoryEntry encodedSCPHistoryEntry) throws IOException { + stream.writeInt(encodedSCPHistoryEntry.getDiscriminant().intValue()); + switch (encodedSCPHistoryEntry.getDiscriminant()) { + case 0: + SCPHistoryEntryV0.encode(stream, encodedSCPHistoryEntry.v0); + break; + } + } + public static SCPHistoryEntry decode(XdrDataInputStream stream) throws IOException { + SCPHistoryEntry decodedSCPHistoryEntry = new SCPHistoryEntry(); + Integer discriminant = stream.readInt(); + decodedSCPHistoryEntry.setDiscriminant(discriminant); + switch (decodedSCPHistoryEntry.getDiscriminant()) { + case 0: + decodedSCPHistoryEntry.v0 = SCPHistoryEntryV0.decode(stream); + break; + } + return decodedSCPHistoryEntry; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SCPHistoryEntryV0.java b/app/src/main/java/org/stellar/sdk/xdr/SCPHistoryEntryV0.java new file mode 100644 index 0000000000..3e0383f285 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SCPHistoryEntryV0.java @@ -0,0 +1,52 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct SCPHistoryEntryV0 +// { +// SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages +// LedgerSCPMessages ledgerMessages; +// }; + +// =========================================================================== +public class SCPHistoryEntryV0 { + public SCPHistoryEntryV0 () {} + private SCPQuorumSet[] quorumSets; + public SCPQuorumSet[] getQuorumSets() { + return this.quorumSets; + } + public void setQuorumSets(SCPQuorumSet[] value) { + this.quorumSets = value; + } + private LedgerSCPMessages ledgerMessages; + public LedgerSCPMessages getLedgerMessages() { + return this.ledgerMessages; + } + public void setLedgerMessages(LedgerSCPMessages value) { + this.ledgerMessages = value; + } + public static void encode(XdrDataOutputStream stream, SCPHistoryEntryV0 encodedSCPHistoryEntryV0) throws IOException{ + int quorumSetssize = encodedSCPHistoryEntryV0.getQuorumSets().length; + stream.writeInt(quorumSetssize); + for (int i = 0; i < quorumSetssize; i++) { + SCPQuorumSet.encode(stream, encodedSCPHistoryEntryV0.quorumSets[i]); + } + LedgerSCPMessages.encode(stream, encodedSCPHistoryEntryV0.ledgerMessages); + } + public static SCPHistoryEntryV0 decode(XdrDataInputStream stream) throws IOException { + SCPHistoryEntryV0 decodedSCPHistoryEntryV0 = new SCPHistoryEntryV0(); + int quorumSetssize = stream.readInt(); + decodedSCPHistoryEntryV0.quorumSets = new SCPQuorumSet[quorumSetssize]; + for (int i = 0; i < quorumSetssize; i++) { + decodedSCPHistoryEntryV0.quorumSets[i] = SCPQuorumSet.decode(stream); + } + decodedSCPHistoryEntryV0.ledgerMessages = LedgerSCPMessages.decode(stream); + return decodedSCPHistoryEntryV0; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SCPNomination.java b/app/src/main/java/org/stellar/sdk/xdr/SCPNomination.java new file mode 100644 index 0000000000..d596ee3ab0 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SCPNomination.java @@ -0,0 +1,70 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct SCPNomination +// { +// Hash quorumSetHash; // D +// Value votes<>; // X +// Value accepted<>; // Y +// }; + +// =========================================================================== +public class SCPNomination { + public SCPNomination () {} + private Hash quorumSetHash; + public Hash getQuorumSetHash() { + return this.quorumSetHash; + } + public void setQuorumSetHash(Hash value) { + this.quorumSetHash = value; + } + private Value[] votes; + public Value[] getVotes() { + return this.votes; + } + public void setVotes(Value[] value) { + this.votes = value; + } + private Value[] accepted; + public Value[] getAccepted() { + return this.accepted; + } + public void setAccepted(Value[] value) { + this.accepted = value; + } + public static void encode(XdrDataOutputStream stream, SCPNomination encodedSCPNomination) throws IOException{ + Hash.encode(stream, encodedSCPNomination.quorumSetHash); + int votessize = encodedSCPNomination.getVotes().length; + stream.writeInt(votessize); + for (int i = 0; i < votessize; i++) { + Value.encode(stream, encodedSCPNomination.votes[i]); + } + int acceptedsize = encodedSCPNomination.getAccepted().length; + stream.writeInt(acceptedsize); + for (int i = 0; i < acceptedsize; i++) { + Value.encode(stream, encodedSCPNomination.accepted[i]); + } + } + public static SCPNomination decode(XdrDataInputStream stream) throws IOException { + SCPNomination decodedSCPNomination = new SCPNomination(); + decodedSCPNomination.quorumSetHash = Hash.decode(stream); + int votessize = stream.readInt(); + decodedSCPNomination.votes = new Value[votessize]; + for (int i = 0; i < votessize; i++) { + decodedSCPNomination.votes[i] = Value.decode(stream); + } + int acceptedsize = stream.readInt(); + decodedSCPNomination.accepted = new Value[acceptedsize]; + for (int i = 0; i < acceptedsize; i++) { + decodedSCPNomination.accepted[i] = Value.decode(stream); + } + return decodedSCPNomination; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SCPQuorumSet.java b/app/src/main/java/org/stellar/sdk/xdr/SCPQuorumSet.java new file mode 100644 index 0000000000..7bb86f9a72 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SCPQuorumSet.java @@ -0,0 +1,70 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct SCPQuorumSet +// { +// uint32 threshold; +// PublicKey validators<>; +// SCPQuorumSet innerSets<>; +// }; + +// =========================================================================== +public class SCPQuorumSet { + public SCPQuorumSet () {} + private Uint32 threshold; + public Uint32 getThreshold() { + return this.threshold; + } + public void setThreshold(Uint32 value) { + this.threshold = value; + } + private PublicKey[] validators; + public PublicKey[] getValidators() { + return this.validators; + } + public void setValidators(PublicKey[] value) { + this.validators = value; + } + private SCPQuorumSet[] innerSets; + public SCPQuorumSet[] getInnerSets() { + return this.innerSets; + } + public void setInnerSets(SCPQuorumSet[] value) { + this.innerSets = value; + } + public static void encode(XdrDataOutputStream stream, SCPQuorumSet encodedSCPQuorumSet) throws IOException{ + Uint32.encode(stream, encodedSCPQuorumSet.threshold); + int validatorssize = encodedSCPQuorumSet.getValidators().length; + stream.writeInt(validatorssize); + for (int i = 0; i < validatorssize; i++) { + PublicKey.encode(stream, encodedSCPQuorumSet.validators[i]); + } + int innerSetssize = encodedSCPQuorumSet.getInnerSets().length; + stream.writeInt(innerSetssize); + for (int i = 0; i < innerSetssize; i++) { + SCPQuorumSet.encode(stream, encodedSCPQuorumSet.innerSets[i]); + } + } + public static SCPQuorumSet decode(XdrDataInputStream stream) throws IOException { + SCPQuorumSet decodedSCPQuorumSet = new SCPQuorumSet(); + decodedSCPQuorumSet.threshold = Uint32.decode(stream); + int validatorssize = stream.readInt(); + decodedSCPQuorumSet.validators = new PublicKey[validatorssize]; + for (int i = 0; i < validatorssize; i++) { + decodedSCPQuorumSet.validators[i] = PublicKey.decode(stream); + } + int innerSetssize = stream.readInt(); + decodedSCPQuorumSet.innerSets = new SCPQuorumSet[innerSetssize]; + for (int i = 0; i < innerSetssize; i++) { + decodedSCPQuorumSet.innerSets[i] = SCPQuorumSet.decode(stream); + } + return decodedSCPQuorumSet; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SCPStatement.java b/app/src/main/java/org/stellar/sdk/xdr/SCPStatement.java new file mode 100644 index 0000000000..35d4df5dbd --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SCPStatement.java @@ -0,0 +1,335 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct SCPStatement +// { +// NodeID nodeID; // v +// uint64 slotIndex; // i +// +// union switch (SCPStatementType type) +// { +// case SCP_ST_PREPARE: +// struct +// { +// Hash quorumSetHash; // D +// SCPBallot ballot; // b +// SCPBallot* prepared; // p +// SCPBallot* preparedPrime; // p' +// uint32 nC; // c.n +// uint32 nH; // h.n +// } prepare; +// case SCP_ST_CONFIRM: +// struct +// { +// SCPBallot ballot; // b +// uint32 nPrepared; // p.n +// uint32 nCommit; // c.n +// uint32 nH; // h.n +// Hash quorumSetHash; // D +// } confirm; +// case SCP_ST_EXTERNALIZE: +// struct +// { +// SCPBallot commit; // c +// uint32 nH; // h.n +// Hash commitQuorumSetHash; // D used before EXTERNALIZE +// } externalize; +// case SCP_ST_NOMINATE: +// SCPNomination nominate; +// } +// pledges; +// }; + +// =========================================================================== +public class SCPStatement { + public SCPStatement () {} + private NodeID nodeID; + public NodeID getNodeID() { + return this.nodeID; + } + public void setNodeID(NodeID value) { + this.nodeID = value; + } + private Uint64 slotIndex; + public Uint64 getSlotIndex() { + return this.slotIndex; + } + public void setSlotIndex(Uint64 value) { + this.slotIndex = value; + } + private SCPStatementPledges pledges; + public SCPStatementPledges getPledges() { + return this.pledges; + } + public void setPledges(SCPStatementPledges value) { + this.pledges = value; + } + public static void encode(XdrDataOutputStream stream, SCPStatement encodedSCPStatement) throws IOException{ + NodeID.encode(stream, encodedSCPStatement.nodeID); + Uint64.encode(stream, encodedSCPStatement.slotIndex); + SCPStatementPledges.encode(stream, encodedSCPStatement.pledges); + } + public static SCPStatement decode(XdrDataInputStream stream) throws IOException { + SCPStatement decodedSCPStatement = new SCPStatement(); + decodedSCPStatement.nodeID = NodeID.decode(stream); + decodedSCPStatement.slotIndex = Uint64.decode(stream); + decodedSCPStatement.pledges = SCPStatementPledges.decode(stream); + return decodedSCPStatement; + } + + public static class SCPStatementPledges { + public SCPStatementPledges () {} + SCPStatementType type; + public SCPStatementType getDiscriminant() { + return this.type; + } + public void setDiscriminant(SCPStatementType value) { + this.type = value; + } + private SCPStatementPrepare prepare; + public SCPStatementPrepare getPrepare() { + return this.prepare; + } + public void setPrepare(SCPStatementPrepare value) { + this.prepare = value; + } + private SCPStatementConfirm confirm; + public SCPStatementConfirm getConfirm() { + return this.confirm; + } + public void setConfirm(SCPStatementConfirm value) { + this.confirm = value; + } + private SCPStatementExternalize externalize; + public SCPStatementExternalize getExternalize() { + return this.externalize; + } + public void setExternalize(SCPStatementExternalize value) { + this.externalize = value; + } + private SCPNomination nominate; + public SCPNomination getNominate() { + return this.nominate; + } + public void setNominate(SCPNomination value) { + this.nominate = value; + } + public static void encode(XdrDataOutputStream stream, SCPStatementPledges encodedSCPStatementPledges) throws IOException { + stream.writeInt(encodedSCPStatementPledges.getDiscriminant().getValue()); + switch (encodedSCPStatementPledges.getDiscriminant()) { + case SCP_ST_PREPARE: + SCPStatementPrepare.encode(stream, encodedSCPStatementPledges.prepare); + break; + case SCP_ST_CONFIRM: + SCPStatementConfirm.encode(stream, encodedSCPStatementPledges.confirm); + break; + case SCP_ST_EXTERNALIZE: + SCPStatementExternalize.encode(stream, encodedSCPStatementPledges.externalize); + break; + case SCP_ST_NOMINATE: + SCPNomination.encode(stream, encodedSCPStatementPledges.nominate); + break; + } + } + public static SCPStatementPledges decode(XdrDataInputStream stream) throws IOException { + SCPStatementPledges decodedSCPStatementPledges = new SCPStatementPledges(); + SCPStatementType discriminant = SCPStatementType.decode(stream); + decodedSCPStatementPledges.setDiscriminant(discriminant); + switch (decodedSCPStatementPledges.getDiscriminant()) { + case SCP_ST_PREPARE: + decodedSCPStatementPledges.prepare = SCPStatementPrepare.decode(stream); + break; + case SCP_ST_CONFIRM: + decodedSCPStatementPledges.confirm = SCPStatementConfirm.decode(stream); + break; + case SCP_ST_EXTERNALIZE: + decodedSCPStatementPledges.externalize = SCPStatementExternalize.decode(stream); + break; + case SCP_ST_NOMINATE: + decodedSCPStatementPledges.nominate = SCPNomination.decode(stream); + break; + } + return decodedSCPStatementPledges; + } + + public static class SCPStatementPrepare { + public SCPStatementPrepare () {} + private Hash quorumSetHash; + public Hash getQuorumSetHash() { + return this.quorumSetHash; + } + public void setQuorumSetHash(Hash value) { + this.quorumSetHash = value; + } + private SCPBallot ballot; + public SCPBallot getBallot() { + return this.ballot; + } + public void setBallot(SCPBallot value) { + this.ballot = value; + } + private SCPBallot prepared; + public SCPBallot getPrepared() { + return this.prepared; + } + public void setPrepared(SCPBallot value) { + this.prepared = value; + } + private SCPBallot preparedPrime; + public SCPBallot getPreparedPrime() { + return this.preparedPrime; + } + public void setPreparedPrime(SCPBallot value) { + this.preparedPrime = value; + } + private Uint32 nC; + public Uint32 getNC() { + return this.nC; + } + public void setNC(Uint32 value) { + this.nC = value; + } + private Uint32 nH; + public Uint32 getNH() { + return this.nH; + } + public void setNH(Uint32 value) { + this.nH = value; + } + public static void encode(XdrDataOutputStream stream, SCPStatementPrepare encodedSCPStatementPrepare) throws IOException{ + Hash.encode(stream, encodedSCPStatementPrepare.quorumSetHash); + SCPBallot.encode(stream, encodedSCPStatementPrepare.ballot); + if (encodedSCPStatementPrepare.prepared != null) { + stream.writeInt(1); + SCPBallot.encode(stream, encodedSCPStatementPrepare.prepared); + } else { + stream.writeInt(0); + } + if (encodedSCPStatementPrepare.preparedPrime != null) { + stream.writeInt(1); + SCPBallot.encode(stream, encodedSCPStatementPrepare.preparedPrime); + } else { + stream.writeInt(0); + } + Uint32.encode(stream, encodedSCPStatementPrepare.nC); + Uint32.encode(stream, encodedSCPStatementPrepare.nH); + } + public static SCPStatementPrepare decode(XdrDataInputStream stream) throws IOException { + SCPStatementPrepare decodedSCPStatementPrepare = new SCPStatementPrepare(); + decodedSCPStatementPrepare.quorumSetHash = Hash.decode(stream); + decodedSCPStatementPrepare.ballot = SCPBallot.decode(stream); + int preparedPresent = stream.readInt(); + if (preparedPresent != 0) { + decodedSCPStatementPrepare.prepared = SCPBallot.decode(stream); + } + int preparedPrimePresent = stream.readInt(); + if (preparedPrimePresent != 0) { + decodedSCPStatementPrepare.preparedPrime = SCPBallot.decode(stream); + } + decodedSCPStatementPrepare.nC = Uint32.decode(stream); + decodedSCPStatementPrepare.nH = Uint32.decode(stream); + return decodedSCPStatementPrepare; + } + + } + public static class SCPStatementConfirm { + public SCPStatementConfirm () {} + private SCPBallot ballot; + public SCPBallot getBallot() { + return this.ballot; + } + public void setBallot(SCPBallot value) { + this.ballot = value; + } + private Uint32 nPrepared; + public Uint32 getNPrepared() { + return this.nPrepared; + } + public void setNPrepared(Uint32 value) { + this.nPrepared = value; + } + private Uint32 nCommit; + public Uint32 getNCommit() { + return this.nCommit; + } + public void setNCommit(Uint32 value) { + this.nCommit = value; + } + private Uint32 nH; + public Uint32 getNH() { + return this.nH; + } + public void setNH(Uint32 value) { + this.nH = value; + } + private Hash quorumSetHash; + public Hash getQuorumSetHash() { + return this.quorumSetHash; + } + public void setQuorumSetHash(Hash value) { + this.quorumSetHash = value; + } + public static void encode(XdrDataOutputStream stream, SCPStatementConfirm encodedSCPStatementConfirm) throws IOException{ + SCPBallot.encode(stream, encodedSCPStatementConfirm.ballot); + Uint32.encode(stream, encodedSCPStatementConfirm.nPrepared); + Uint32.encode(stream, encodedSCPStatementConfirm.nCommit); + Uint32.encode(stream, encodedSCPStatementConfirm.nH); + Hash.encode(stream, encodedSCPStatementConfirm.quorumSetHash); + } + public static SCPStatementConfirm decode(XdrDataInputStream stream) throws IOException { + SCPStatementConfirm decodedSCPStatementConfirm = new SCPStatementConfirm(); + decodedSCPStatementConfirm.ballot = SCPBallot.decode(stream); + decodedSCPStatementConfirm.nPrepared = Uint32.decode(stream); + decodedSCPStatementConfirm.nCommit = Uint32.decode(stream); + decodedSCPStatementConfirm.nH = Uint32.decode(stream); + decodedSCPStatementConfirm.quorumSetHash = Hash.decode(stream); + return decodedSCPStatementConfirm; + } + + } + public static class SCPStatementExternalize { + public SCPStatementExternalize () {} + private SCPBallot commit; + public SCPBallot getCommit() { + return this.commit; + } + public void setCommit(SCPBallot value) { + this.commit = value; + } + private Uint32 nH; + public Uint32 getNH() { + return this.nH; + } + public void setNH(Uint32 value) { + this.nH = value; + } + private Hash commitQuorumSetHash; + public Hash getCommitQuorumSetHash() { + return this.commitQuorumSetHash; + } + public void setCommitQuorumSetHash(Hash value) { + this.commitQuorumSetHash = value; + } + public static void encode(XdrDataOutputStream stream, SCPStatementExternalize encodedSCPStatementExternalize) throws IOException{ + SCPBallot.encode(stream, encodedSCPStatementExternalize.commit); + Uint32.encode(stream, encodedSCPStatementExternalize.nH); + Hash.encode(stream, encodedSCPStatementExternalize.commitQuorumSetHash); + } + public static SCPStatementExternalize decode(XdrDataInputStream stream) throws IOException { + SCPStatementExternalize decodedSCPStatementExternalize = new SCPStatementExternalize(); + decodedSCPStatementExternalize.commit = SCPBallot.decode(stream); + decodedSCPStatementExternalize.nH = Uint32.decode(stream); + decodedSCPStatementExternalize.commitQuorumSetHash = Hash.decode(stream); + return decodedSCPStatementExternalize; + } + + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SCPStatementType.java b/app/src/main/java/org/stellar/sdk/xdr/SCPStatementType.java new file mode 100644 index 0000000000..701770aa8b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SCPStatementType.java @@ -0,0 +1,51 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum SCPStatementType +// { +// SCP_ST_PREPARE = 0, +// SCP_ST_CONFIRM = 1, +// SCP_ST_EXTERNALIZE = 2, +// SCP_ST_NOMINATE = 3 +// }; + +// =========================================================================== +public enum SCPStatementType { + SCP_ST_PREPARE(0), + SCP_ST_CONFIRM(1), + SCP_ST_EXTERNALIZE(2), + SCP_ST_NOMINATE(3), + ; + private int mValue; + + SCPStatementType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static SCPStatementType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return SCP_ST_PREPARE; + case 1: return SCP_ST_CONFIRM; + case 2: return SCP_ST_EXTERNALIZE; + case 3: return SCP_ST_NOMINATE; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, SCPStatementType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SequenceNumber.java b/app/src/main/java/org/stellar/sdk/xdr/SequenceNumber.java new file mode 100644 index 0000000000..1db4e317e7 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SequenceNumber.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef int64 SequenceNumber; + +// =========================================================================== +public class SequenceNumber { + private Int64 SequenceNumber; + public Int64 getSequenceNumber() { + return this.SequenceNumber; + } + public void setSequenceNumber(Int64 value) { + this.SequenceNumber = value; + } + public static void encode(XdrDataOutputStream stream, SequenceNumber encodedSequenceNumber) throws IOException { + Int64.encode(stream, encodedSequenceNumber.SequenceNumber); + } + public static SequenceNumber decode(XdrDataInputStream stream) throws IOException { + SequenceNumber decodedSequenceNumber = new SequenceNumber(); + decodedSequenceNumber.SequenceNumber = Int64.decode(stream); + return decodedSequenceNumber; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SetOptionsOp.java b/app/src/main/java/org/stellar/sdk/xdr/SetOptionsOp.java new file mode 100644 index 0000000000..7071b1aec2 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SetOptionsOp.java @@ -0,0 +1,193 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct SetOptionsOp +// { +// AccountID* inflationDest; // sets the inflation destination +// +// uint32* clearFlags; // which flags to clear +// uint32* setFlags; // which flags to set +// +// // account threshold manipulation +// uint32* masterWeight; // weight of the master account +// uint32* lowThreshold; +// uint32* medThreshold; +// uint32* highThreshold; +// +// string32* homeDomain; // sets the home domain +// +// // Add, update or remove a signer for the account +// // signer is deleted if the weight is 0 +// Signer* signer; +// }; + +// =========================================================================== +public class SetOptionsOp { + public SetOptionsOp () {} + private AccountID inflationDest; + public AccountID getInflationDest() { + return this.inflationDest; + } + public void setInflationDest(AccountID value) { + this.inflationDest = value; + } + private Uint32 clearFlags; + public Uint32 getClearFlags() { + return this.clearFlags; + } + public void setClearFlags(Uint32 value) { + this.clearFlags = value; + } + private Uint32 setFlags; + public Uint32 getSetFlags() { + return this.setFlags; + } + public void setSetFlags(Uint32 value) { + this.setFlags = value; + } + private Uint32 masterWeight; + public Uint32 getMasterWeight() { + return this.masterWeight; + } + public void setMasterWeight(Uint32 value) { + this.masterWeight = value; + } + private Uint32 lowThreshold; + public Uint32 getLowThreshold() { + return this.lowThreshold; + } + public void setLowThreshold(Uint32 value) { + this.lowThreshold = value; + } + private Uint32 medThreshold; + public Uint32 getMedThreshold() { + return this.medThreshold; + } + public void setMedThreshold(Uint32 value) { + this.medThreshold = value; + } + private Uint32 highThreshold; + public Uint32 getHighThreshold() { + return this.highThreshold; + } + public void setHighThreshold(Uint32 value) { + this.highThreshold = value; + } + private String32 homeDomain; + public String32 getHomeDomain() { + return this.homeDomain; + } + public void setHomeDomain(String32 value) { + this.homeDomain = value; + } + private Signer signer; + public Signer getSigner() { + return this.signer; + } + public void setSigner(Signer value) { + this.signer = value; + } + public static void encode(XdrDataOutputStream stream, SetOptionsOp encodedSetOptionsOp) throws IOException{ + if (encodedSetOptionsOp.inflationDest != null) { + stream.writeInt(1); + AccountID.encode(stream, encodedSetOptionsOp.inflationDest); + } else { + stream.writeInt(0); + } + if (encodedSetOptionsOp.clearFlags != null) { + stream.writeInt(1); + Uint32.encode(stream, encodedSetOptionsOp.clearFlags); + } else { + stream.writeInt(0); + } + if (encodedSetOptionsOp.setFlags != null) { + stream.writeInt(1); + Uint32.encode(stream, encodedSetOptionsOp.setFlags); + } else { + stream.writeInt(0); + } + if (encodedSetOptionsOp.masterWeight != null) { + stream.writeInt(1); + Uint32.encode(stream, encodedSetOptionsOp.masterWeight); + } else { + stream.writeInt(0); + } + if (encodedSetOptionsOp.lowThreshold != null) { + stream.writeInt(1); + Uint32.encode(stream, encodedSetOptionsOp.lowThreshold); + } else { + stream.writeInt(0); + } + if (encodedSetOptionsOp.medThreshold != null) { + stream.writeInt(1); + Uint32.encode(stream, encodedSetOptionsOp.medThreshold); + } else { + stream.writeInt(0); + } + if (encodedSetOptionsOp.highThreshold != null) { + stream.writeInt(1); + Uint32.encode(stream, encodedSetOptionsOp.highThreshold); + } else { + stream.writeInt(0); + } + if (encodedSetOptionsOp.homeDomain != null) { + stream.writeInt(1); + String32.encode(stream, encodedSetOptionsOp.homeDomain); + } else { + stream.writeInt(0); + } + if (encodedSetOptionsOp.signer != null) { + stream.writeInt(1); + Signer.encode(stream, encodedSetOptionsOp.signer); + } else { + stream.writeInt(0); + } + } + public static SetOptionsOp decode(XdrDataInputStream stream) throws IOException { + SetOptionsOp decodedSetOptionsOp = new SetOptionsOp(); + int inflationDestPresent = stream.readInt(); + if (inflationDestPresent != 0) { + decodedSetOptionsOp.inflationDest = AccountID.decode(stream); + } + int clearFlagsPresent = stream.readInt(); + if (clearFlagsPresent != 0) { + decodedSetOptionsOp.clearFlags = Uint32.decode(stream); + } + int setFlagsPresent = stream.readInt(); + if (setFlagsPresent != 0) { + decodedSetOptionsOp.setFlags = Uint32.decode(stream); + } + int masterWeightPresent = stream.readInt(); + if (masterWeightPresent != 0) { + decodedSetOptionsOp.masterWeight = Uint32.decode(stream); + } + int lowThresholdPresent = stream.readInt(); + if (lowThresholdPresent != 0) { + decodedSetOptionsOp.lowThreshold = Uint32.decode(stream); + } + int medThresholdPresent = stream.readInt(); + if (medThresholdPresent != 0) { + decodedSetOptionsOp.medThreshold = Uint32.decode(stream); + } + int highThresholdPresent = stream.readInt(); + if (highThresholdPresent != 0) { + decodedSetOptionsOp.highThreshold = Uint32.decode(stream); + } + int homeDomainPresent = stream.readInt(); + if (homeDomainPresent != 0) { + decodedSetOptionsOp.homeDomain = String32.decode(stream); + } + int signerPresent = stream.readInt(); + if (signerPresent != 0) { + decodedSetOptionsOp.signer = Signer.decode(stream); + } + return decodedSetOptionsOp; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SetOptionsResult.java b/app/src/main/java/org/stellar/sdk/xdr/SetOptionsResult.java new file mode 100644 index 0000000000..cb6a409505 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SetOptionsResult.java @@ -0,0 +1,50 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union SetOptionsResult switch (SetOptionsResultCode code) +// { +// case SET_OPTIONS_SUCCESS: +// void; +// default: +// void; +// }; + +// =========================================================================== +public class SetOptionsResult { + public SetOptionsResult () {} + SetOptionsResultCode code; + public SetOptionsResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(SetOptionsResultCode value) { + this.code = value; + } + public static void encode(XdrDataOutputStream stream, SetOptionsResult encodedSetOptionsResult) throws IOException { + stream.writeInt(encodedSetOptionsResult.getDiscriminant().getValue()); + switch (encodedSetOptionsResult.getDiscriminant()) { + case SET_OPTIONS_SUCCESS: + break; + default: + break; + } + } + public static SetOptionsResult decode(XdrDataInputStream stream) throws IOException { + SetOptionsResult decodedSetOptionsResult = new SetOptionsResult(); + SetOptionsResultCode discriminant = SetOptionsResultCode.decode(stream); + decodedSetOptionsResult.setDiscriminant(discriminant); + switch (decodedSetOptionsResult.getDiscriminant()) { + case SET_OPTIONS_SUCCESS: + break; + default: + break; + } + return decodedSetOptionsResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SetOptionsResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/SetOptionsResultCode.java new file mode 100644 index 0000000000..8ab2adbdda --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SetOptionsResultCode.java @@ -0,0 +1,71 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum SetOptionsResultCode +// { +// // codes considered as "success" for the operation +// SET_OPTIONS_SUCCESS = 0, +// // codes considered as "failure" for the operation +// SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer +// SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached +// SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags +// SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist +// SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option +// SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag +// SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold +// SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey +// SET_OPTIONS_INVALID_HOME_DOMAIN = -9 // malformed home domain +// }; + +// =========================================================================== +public enum SetOptionsResultCode { + SET_OPTIONS_SUCCESS(0), + SET_OPTIONS_LOW_RESERVE(-1), + SET_OPTIONS_TOO_MANY_SIGNERS(-2), + SET_OPTIONS_BAD_FLAGS(-3), + SET_OPTIONS_INVALID_INFLATION(-4), + SET_OPTIONS_CANT_CHANGE(-5), + SET_OPTIONS_UNKNOWN_FLAG(-6), + SET_OPTIONS_THRESHOLD_OUT_OF_RANGE(-7), + SET_OPTIONS_BAD_SIGNER(-8), + SET_OPTIONS_INVALID_HOME_DOMAIN(-9), + ; + private int mValue; + + SetOptionsResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static SetOptionsResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return SET_OPTIONS_SUCCESS; + case -1: return SET_OPTIONS_LOW_RESERVE; + case -2: return SET_OPTIONS_TOO_MANY_SIGNERS; + case -3: return SET_OPTIONS_BAD_FLAGS; + case -4: return SET_OPTIONS_INVALID_INFLATION; + case -5: return SET_OPTIONS_CANT_CHANGE; + case -6: return SET_OPTIONS_UNKNOWN_FLAG; + case -7: return SET_OPTIONS_THRESHOLD_OUT_OF_RANGE; + case -8: return SET_OPTIONS_BAD_SIGNER; + case -9: return SET_OPTIONS_INVALID_HOME_DOMAIN; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, SetOptionsResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Signature.java b/app/src/main/java/org/stellar/sdk/xdr/Signature.java new file mode 100644 index 0000000000..34cc005d8e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Signature.java @@ -0,0 +1,34 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef opaque Signature<64>; + +// =========================================================================== +public class Signature { + private byte[] Signature; + public byte[] getSignature() { + return this.Signature; + } + public void setSignature(byte[] value) { + this.Signature = value; + } + public static void encode(XdrDataOutputStream stream, Signature encodedSignature) throws IOException { + int Signaturesize = encodedSignature.Signature.length; + stream.writeInt(Signaturesize); + stream.write(encodedSignature.getSignature(), 0, Signaturesize); + } + public static Signature decode(XdrDataInputStream stream) throws IOException { + Signature decodedSignature = new Signature(); + int Signaturesize = stream.readInt(); + decodedSignature.Signature = new byte[Signaturesize]; + stream.read(decodedSignature.Signature, 0, Signaturesize); + return decodedSignature; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SignatureHint.java b/app/src/main/java/org/stellar/sdk/xdr/SignatureHint.java new file mode 100644 index 0000000000..e7aacc0a2e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SignatureHint.java @@ -0,0 +1,33 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef opaque SignatureHint[4]; + +// =========================================================================== +public class SignatureHint { + private byte[] SignatureHint; + public byte[] getSignatureHint() { + return this.SignatureHint; + } + public void setSignatureHint(byte[] value) { + this.SignatureHint = value; + } + public static void encode(XdrDataOutputStream stream, SignatureHint encodedSignatureHint) throws IOException { + int SignatureHintsize = encodedSignatureHint.SignatureHint.length; + stream.write(encodedSignatureHint.getSignatureHint(), 0, SignatureHintsize); + } + public static SignatureHint decode(XdrDataInputStream stream) throws IOException { + SignatureHint decodedSignatureHint = new SignatureHint(); + int SignatureHintsize = 4; + decodedSignatureHint.SignatureHint = new byte[SignatureHintsize]; + stream.read(decodedSignatureHint.SignatureHint, 0, SignatureHintsize); + return decodedSignatureHint; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Signer.java b/app/src/main/java/org/stellar/sdk/xdr/Signer.java new file mode 100644 index 0000000000..68216ae07a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Signer.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Signer +// { +// SignerKey key; +// uint32 weight; // really only need 1byte +// }; + +// =========================================================================== +public class Signer { + public Signer () {} + private SignerKey key; + public SignerKey getKey() { + return this.key; + } + public void setKey(SignerKey value) { + this.key = value; + } + private Uint32 weight; + public Uint32 getWeight() { + return this.weight; + } + public void setWeight(Uint32 value) { + this.weight = value; + } + public static void encode(XdrDataOutputStream stream, Signer encodedSigner) throws IOException{ + SignerKey.encode(stream, encodedSigner.key); + Uint32.encode(stream, encodedSigner.weight); + } + public static Signer decode(XdrDataInputStream stream) throws IOException { + Signer decodedSigner = new Signer(); + decodedSigner.key = SignerKey.decode(stream); + decodedSigner.weight = Uint32.decode(stream); + return decodedSigner; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SignerKey.java b/app/src/main/java/org/stellar/sdk/xdr/SignerKey.java new file mode 100644 index 0000000000..279ffb4bfe --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SignerKey.java @@ -0,0 +1,85 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union SignerKey switch (SignerKeyType type) +// { +// case SIGNER_KEY_TYPE_ED25519: +// uint256 ed25519; +// case SIGNER_KEY_TYPE_PRE_AUTH_TX: +// /* SHA-256 Hash of TransactionSignaturePayload structure */ +// uint256 preAuthTx; +// case SIGNER_KEY_TYPE_HASH_X: +// /* Hash of random 256 bit preimage X */ +// uint256 hashX; +// }; + +// =========================================================================== +public class SignerKey { + public SignerKey () {} + SignerKeyType type; + public SignerKeyType getDiscriminant() { + return this.type; + } + public void setDiscriminant(SignerKeyType value) { + this.type = value; + } + private Uint256 ed25519; + public Uint256 getEd25519() { + return this.ed25519; + } + public void setEd25519(Uint256 value) { + this.ed25519 = value; + } + private Uint256 preAuthTx; + public Uint256 getPreAuthTx() { + return this.preAuthTx; + } + public void setPreAuthTx(Uint256 value) { + this.preAuthTx = value; + } + private Uint256 hashX; + public Uint256 getHashX() { + return this.hashX; + } + public void setHashX(Uint256 value) { + this.hashX = value; + } + public static void encode(XdrDataOutputStream stream, SignerKey encodedSignerKey) throws IOException { + stream.writeInt(encodedSignerKey.getDiscriminant().getValue()); + switch (encodedSignerKey.getDiscriminant()) { + case SIGNER_KEY_TYPE_ED25519: + Uint256.encode(stream, encodedSignerKey.ed25519); + break; + case SIGNER_KEY_TYPE_PRE_AUTH_TX: + Uint256.encode(stream, encodedSignerKey.preAuthTx); + break; + case SIGNER_KEY_TYPE_HASH_X: + Uint256.encode(stream, encodedSignerKey.hashX); + break; + } + } + public static SignerKey decode(XdrDataInputStream stream) throws IOException { + SignerKey decodedSignerKey = new SignerKey(); + SignerKeyType discriminant = SignerKeyType.decode(stream); + decodedSignerKey.setDiscriminant(discriminant); + switch (decodedSignerKey.getDiscriminant()) { + case SIGNER_KEY_TYPE_ED25519: + decodedSignerKey.ed25519 = Uint256.decode(stream); + break; + case SIGNER_KEY_TYPE_PRE_AUTH_TX: + decodedSignerKey.preAuthTx = Uint256.decode(stream); + break; + case SIGNER_KEY_TYPE_HASH_X: + decodedSignerKey.hashX = Uint256.decode(stream); + break; + } + return decodedSignerKey; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SignerKeyType.java b/app/src/main/java/org/stellar/sdk/xdr/SignerKeyType.java new file mode 100644 index 0000000000..8cc0364ede --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SignerKeyType.java @@ -0,0 +1,48 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum SignerKeyType +// { +// SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519, +// SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX, +// SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X +// }; + +// =========================================================================== +public enum SignerKeyType { + SIGNER_KEY_TYPE_ED25519(0), + SIGNER_KEY_TYPE_PRE_AUTH_TX(1), + SIGNER_KEY_TYPE_HASH_X(2), + ; + private int mValue; + + SignerKeyType(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static SignerKeyType decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return SIGNER_KEY_TYPE_ED25519; + case 1: return SIGNER_KEY_TYPE_PRE_AUTH_TX; + case 2: return SIGNER_KEY_TYPE_HASH_X; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, SignerKeyType value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/SimplePaymentResult.java b/app/src/main/java/org/stellar/sdk/xdr/SimplePaymentResult.java new file mode 100644 index 0000000000..e25e7c0fdd --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/SimplePaymentResult.java @@ -0,0 +1,54 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct SimplePaymentResult +// { +// AccountID destination; +// Asset asset; +// int64 amount; +// }; + +// =========================================================================== +public class SimplePaymentResult { + public SimplePaymentResult () {} + private AccountID destination; + public AccountID getDestination() { + return this.destination; + } + public void setDestination(AccountID value) { + this.destination = value; + } + private Asset asset; + public Asset getAsset() { + return this.asset; + } + public void setAsset(Asset value) { + this.asset = value; + } + private Int64 amount; + public Int64 getAmount() { + return this.amount; + } + public void setAmount(Int64 value) { + this.amount = value; + } + public static void encode(XdrDataOutputStream stream, SimplePaymentResult encodedSimplePaymentResult) throws IOException{ + AccountID.encode(stream, encodedSimplePaymentResult.destination); + Asset.encode(stream, encodedSimplePaymentResult.asset); + Int64.encode(stream, encodedSimplePaymentResult.amount); + } + public static SimplePaymentResult decode(XdrDataInputStream stream) throws IOException { + SimplePaymentResult decodedSimplePaymentResult = new SimplePaymentResult(); + decodedSimplePaymentResult.destination = AccountID.decode(stream); + decodedSimplePaymentResult.asset = Asset.decode(stream); + decodedSimplePaymentResult.amount = Int64.decode(stream); + return decodedSimplePaymentResult; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/StellarMessage.java b/app/src/main/java/org/stellar/sdk/xdr/StellarMessage.java new file mode 100644 index 0000000000..4c2a9656b2 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/StellarMessage.java @@ -0,0 +1,236 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union StellarMessage switch (MessageType type) +// { +// case ERROR_MSG: +// Error error; +// case HELLO: +// Hello hello; +// case AUTH: +// Auth auth; +// case DONT_HAVE: +// DontHave dontHave; +// case GET_PEERS: +// void; +// case PEERS: +// PeerAddress peers<100>; +// +// case GET_TX_SET: +// uint256 txSetHash; +// case TX_SET: +// TransactionSet txSet; +// +// case TRANSACTION: +// TransactionEnvelope transaction; +// +// // SCP +// case GET_SCP_QUORUMSET: +// uint256 qSetHash; +// case SCP_QUORUMSET: +// SCPQuorumSet qSet; +// case SCP_MESSAGE: +// SCPEnvelope envelope; +// case GET_SCP_STATE: +// uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest +// }; + +// =========================================================================== +public class StellarMessage { + public StellarMessage () {} + MessageType type; + public MessageType getDiscriminant() { + return this.type; + } + public void setDiscriminant(MessageType value) { + this.type = value; + } + private Error error; + public Error getError() { + return this.error; + } + public void setError(Error value) { + this.error = value; + } + private Hello hello; + public Hello getHello() { + return this.hello; + } + public void setHello(Hello value) { + this.hello = value; + } + private Auth auth; + public Auth getAuth() { + return this.auth; + } + public void setAuth(Auth value) { + this.auth = value; + } + private DontHave dontHave; + public DontHave getDontHave() { + return this.dontHave; + } + public void setDontHave(DontHave value) { + this.dontHave = value; + } + private PeerAddress[] peers; + public PeerAddress[] getPeers() { + return this.peers; + } + public void setPeers(PeerAddress[] value) { + this.peers = value; + } + private Uint256 txSetHash; + public Uint256 getTxSetHash() { + return this.txSetHash; + } + public void setTxSetHash(Uint256 value) { + this.txSetHash = value; + } + private TransactionSet txSet; + public TransactionSet getTxSet() { + return this.txSet; + } + public void setTxSet(TransactionSet value) { + this.txSet = value; + } + private TransactionEnvelope transaction; + public TransactionEnvelope getTransaction() { + return this.transaction; + } + public void setTransaction(TransactionEnvelope value) { + this.transaction = value; + } + private Uint256 qSetHash; + public Uint256 getQSetHash() { + return this.qSetHash; + } + public void setQSetHash(Uint256 value) { + this.qSetHash = value; + } + private SCPQuorumSet qSet; + public SCPQuorumSet getQSet() { + return this.qSet; + } + public void setQSet(SCPQuorumSet value) { + this.qSet = value; + } + private SCPEnvelope envelope; + public SCPEnvelope getEnvelope() { + return this.envelope; + } + public void setEnvelope(SCPEnvelope value) { + this.envelope = value; + } + private Uint32 getSCPLedgerSeq; + public Uint32 getGetSCPLedgerSeq() { + return this.getSCPLedgerSeq; + } + public void setGetSCPLedgerSeq(Uint32 value) { + this.getSCPLedgerSeq = value; + } + public static void encode(XdrDataOutputStream stream, StellarMessage encodedStellarMessage) throws IOException { + stream.writeInt(encodedStellarMessage.getDiscriminant().getValue()); + switch (encodedStellarMessage.getDiscriminant()) { + case ERROR_MSG: + Error.encode(stream, encodedStellarMessage.error); + break; + case HELLO: + Hello.encode(stream, encodedStellarMessage.hello); + break; + case AUTH: + Auth.encode(stream, encodedStellarMessage.auth); + break; + case DONT_HAVE: + DontHave.encode(stream, encodedStellarMessage.dontHave); + break; + case GET_PEERS: + break; + case PEERS: + int peerssize = encodedStellarMessage.getPeers().length; + stream.writeInt(peerssize); + for (int i = 0; i < peerssize; i++) { + PeerAddress.encode(stream, encodedStellarMessage.peers[i]); + } + break; + case GET_TX_SET: + Uint256.encode(stream, encodedStellarMessage.txSetHash); + break; + case TX_SET: + TransactionSet.encode(stream, encodedStellarMessage.txSet); + break; + case TRANSACTION: + TransactionEnvelope.encode(stream, encodedStellarMessage.transaction); + break; + case GET_SCP_QUORUMSET: + Uint256.encode(stream, encodedStellarMessage.qSetHash); + break; + case SCP_QUORUMSET: + SCPQuorumSet.encode(stream, encodedStellarMessage.qSet); + break; + case SCP_MESSAGE: + SCPEnvelope.encode(stream, encodedStellarMessage.envelope); + break; + case GET_SCP_STATE: + Uint32.encode(stream, encodedStellarMessage.getSCPLedgerSeq); + break; + } + } + public static StellarMessage decode(XdrDataInputStream stream) throws IOException { + StellarMessage decodedStellarMessage = new StellarMessage(); + MessageType discriminant = MessageType.decode(stream); + decodedStellarMessage.setDiscriminant(discriminant); + switch (decodedStellarMessage.getDiscriminant()) { + case ERROR_MSG: + decodedStellarMessage.error = Error.decode(stream); + break; + case HELLO: + decodedStellarMessage.hello = Hello.decode(stream); + break; + case AUTH: + decodedStellarMessage.auth = Auth.decode(stream); + break; + case DONT_HAVE: + decodedStellarMessage.dontHave = DontHave.decode(stream); + break; + case GET_PEERS: + break; + case PEERS: + int peerssize = stream.readInt(); + decodedStellarMessage.peers = new PeerAddress[peerssize]; + for (int i = 0; i < peerssize; i++) { + decodedStellarMessage.peers[i] = PeerAddress.decode(stream); + } + break; + case GET_TX_SET: + decodedStellarMessage.txSetHash = Uint256.decode(stream); + break; + case TX_SET: + decodedStellarMessage.txSet = TransactionSet.decode(stream); + break; + case TRANSACTION: + decodedStellarMessage.transaction = TransactionEnvelope.decode(stream); + break; + case GET_SCP_QUORUMSET: + decodedStellarMessage.qSetHash = Uint256.decode(stream); + break; + case SCP_QUORUMSET: + decodedStellarMessage.qSet = SCPQuorumSet.decode(stream); + break; + case SCP_MESSAGE: + decodedStellarMessage.envelope = SCPEnvelope.decode(stream); + break; + case GET_SCP_STATE: + decodedStellarMessage.getSCPLedgerSeq = Uint32.decode(stream); + break; + } + return decodedStellarMessage; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/StellarValue.java b/app/src/main/java/org/stellar/sdk/xdr/StellarValue.java new file mode 100644 index 0000000000..364303719c --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/StellarValue.java @@ -0,0 +1,114 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct StellarValue +// { +// Hash txSetHash; // transaction set to apply to previous ledger +// uint64 closeTime; // network close time +// +// // upgrades to apply to the previous ledger (usually empty) +// // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop +// // unknown steps during consensus if needed. +// // see notes below on 'LedgerUpgrade' for more detail +// // max size is dictated by number of upgrade types (+ room for future) +// UpgradeType upgrades<6>; +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class StellarValue { + public StellarValue () {} + private Hash txSetHash; + public Hash getTxSetHash() { + return this.txSetHash; + } + public void setTxSetHash(Hash value) { + this.txSetHash = value; + } + private Uint64 closeTime; + public Uint64 getCloseTime() { + return this.closeTime; + } + public void setCloseTime(Uint64 value) { + this.closeTime = value; + } + private UpgradeType[] upgrades; + public UpgradeType[] getUpgrades() { + return this.upgrades; + } + public void setUpgrades(UpgradeType[] value) { + this.upgrades = value; + } + private StellarValueExt ext; + public StellarValueExt getExt() { + return this.ext; + } + public void setExt(StellarValueExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, StellarValue encodedStellarValue) throws IOException{ + Hash.encode(stream, encodedStellarValue.txSetHash); + Uint64.encode(stream, encodedStellarValue.closeTime); + int upgradessize = encodedStellarValue.getUpgrades().length; + stream.writeInt(upgradessize); + for (int i = 0; i < upgradessize; i++) { + UpgradeType.encode(stream, encodedStellarValue.upgrades[i]); + } + StellarValueExt.encode(stream, encodedStellarValue.ext); + } + public static StellarValue decode(XdrDataInputStream stream) throws IOException { + StellarValue decodedStellarValue = new StellarValue(); + decodedStellarValue.txSetHash = Hash.decode(stream); + decodedStellarValue.closeTime = Uint64.decode(stream); + int upgradessize = stream.readInt(); + decodedStellarValue.upgrades = new UpgradeType[upgradessize]; + for (int i = 0; i < upgradessize; i++) { + decodedStellarValue.upgrades[i] = UpgradeType.decode(stream); + } + decodedStellarValue.ext = StellarValueExt.decode(stream); + return decodedStellarValue; + } + + public static class StellarValueExt { + public StellarValueExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, StellarValueExt encodedStellarValueExt) throws IOException { + stream.writeInt(encodedStellarValueExt.getDiscriminant().intValue()); + switch (encodedStellarValueExt.getDiscriminant()) { + case 0: + break; + } + } + public static StellarValueExt decode(XdrDataInputStream stream) throws IOException { + StellarValueExt decodedStellarValueExt = new StellarValueExt(); + Integer discriminant = stream.readInt(); + decodedStellarValueExt.setDiscriminant(discriminant); + switch (decodedStellarValueExt.getDiscriminant()) { + case 0: + break; + } + return decodedStellarValueExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/String32.java b/app/src/main/java/org/stellar/sdk/xdr/String32.java new file mode 100644 index 0000000000..2e974cdeb9 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/String32.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef string string32<32>; + +// =========================================================================== +public class String32 { + private String string32; + public String getString32() { + return this.string32; + } + public void setString32(String value) { + this.string32 = value; + } + public static void encode(XdrDataOutputStream stream, String32 encodedString32) throws IOException { + stream.writeString(encodedString32.string32); + } + public static String32 decode(XdrDataInputStream stream) throws IOException { + String32 decodedString32 = new String32(); + decodedString32.string32 = stream.readString(); + return decodedString32; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/String64.java b/app/src/main/java/org/stellar/sdk/xdr/String64.java new file mode 100644 index 0000000000..de0fe9810e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/String64.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef string string64<64>; + +// =========================================================================== +public class String64 { + private String string64; + public String getString64() { + return this.string64; + } + public void setString64(String value) { + this.string64 = value; + } + public static void encode(XdrDataOutputStream stream, String64 encodedString64) throws IOException { + stream.writeString(encodedString64.string64); + } + public static String64 decode(XdrDataInputStream stream) throws IOException { + String64 decodedString64 = new String64(); + decodedString64.string64 = stream.readString(); + return decodedString64; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ThresholdIndexes.java b/app/src/main/java/org/stellar/sdk/xdr/ThresholdIndexes.java new file mode 100644 index 0000000000..7046e94a22 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ThresholdIndexes.java @@ -0,0 +1,51 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum ThresholdIndexes +// { +// THRESHOLD_MASTER_WEIGHT = 0, +// THRESHOLD_LOW = 1, +// THRESHOLD_MED = 2, +// THRESHOLD_HIGH = 3 +// }; + +// =========================================================================== +public enum ThresholdIndexes { + THRESHOLD_MASTER_WEIGHT(0), + THRESHOLD_LOW(1), + THRESHOLD_MED(2), + THRESHOLD_HIGH(3), + ; + private int mValue; + + ThresholdIndexes(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static ThresholdIndexes decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return THRESHOLD_MASTER_WEIGHT; + case 1: return THRESHOLD_LOW; + case 2: return THRESHOLD_MED; + case 3: return THRESHOLD_HIGH; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, ThresholdIndexes value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/ThresholdIndices.java b/app/src/main/java/org/stellar/sdk/xdr/ThresholdIndices.java new file mode 100644 index 0000000000..89e5f8921b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/ThresholdIndices.java @@ -0,0 +1,51 @@ +// Automatically generated on 2015-11-05T11:21:06-08:00 +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum ThresholdIndexes +// { +// THRESHOLD_MASTER_WEIGHT = 0, +// THRESHOLD_LOW = 1, +// THRESHOLD_MED = 2, +// THRESHOLD_HIGH = 3 +// }; + +// =========================================================================== +public enum ThresholdIndices { + THRESHOLD_MASTER_WEIGHT(0), + THRESHOLD_LOW(1), + THRESHOLD_MED(2), + THRESHOLD_HIGH(3), + ; + private int mValue; + + ThresholdIndices(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static ThresholdIndices decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return THRESHOLD_MASTER_WEIGHT; + case 1: return THRESHOLD_LOW; + case 2: return THRESHOLD_MED; + case 3: return THRESHOLD_HIGH; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, ThresholdIndices value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Thresholds.java b/app/src/main/java/org/stellar/sdk/xdr/Thresholds.java new file mode 100644 index 0000000000..9e7656a8d9 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Thresholds.java @@ -0,0 +1,33 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef opaque Thresholds[4]; + +// =========================================================================== +public class Thresholds { + private byte[] Thresholds; + public byte[] getThresholds() { + return this.Thresholds; + } + public void setThresholds(byte[] value) { + this.Thresholds = value; + } + public static void encode(XdrDataOutputStream stream, Thresholds encodedThresholds) throws IOException { + int Thresholdssize = encodedThresholds.Thresholds.length; + stream.write(encodedThresholds.getThresholds(), 0, Thresholdssize); + } + public static Thresholds decode(XdrDataInputStream stream) throws IOException { + Thresholds decodedThresholds = new Thresholds(); + int Thresholdssize = 4; + decodedThresholds.Thresholds = new byte[Thresholdssize]; + stream.read(decodedThresholds.Thresholds, 0, Thresholdssize); + return decodedThresholds; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TimeBounds.java b/app/src/main/java/org/stellar/sdk/xdr/TimeBounds.java new file mode 100644 index 0000000000..b014b72f07 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TimeBounds.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TimeBounds +// { +// uint64 minTime; +// uint64 maxTime; // 0 here means no maxTime +// }; + +// =========================================================================== +public class TimeBounds { + public TimeBounds () {} + private Uint64 minTime; + public Uint64 getMinTime() { + return this.minTime; + } + public void setMinTime(Uint64 value) { + this.minTime = value; + } + private Uint64 maxTime; + public Uint64 getMaxTime() { + return this.maxTime; + } + public void setMaxTime(Uint64 value) { + this.maxTime = value; + } + public static void encode(XdrDataOutputStream stream, TimeBounds encodedTimeBounds) throws IOException{ + Uint64.encode(stream, encodedTimeBounds.minTime); + Uint64.encode(stream, encodedTimeBounds.maxTime); + } + public static TimeBounds decode(XdrDataInputStream stream) throws IOException { + TimeBounds decodedTimeBounds = new TimeBounds(); + decodedTimeBounds.minTime = Uint64.decode(stream); + decodedTimeBounds.maxTime = Uint64.decode(stream); + return decodedTimeBounds; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Transaction.java b/app/src/main/java/org/stellar/sdk/xdr/Transaction.java new file mode 100644 index 0000000000..7225b06ebf --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Transaction.java @@ -0,0 +1,155 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct Transaction +// { +// // account used to run the transaction +// AccountID sourceAccount; +// +// // the fee the sourceAccount will pay +// uint32 fee; +// +// // sequence number to consume in the account +// SequenceNumber seqNum; +// +// // validity range (inclusive) for the last ledger close time +// TimeBounds* timeBounds; +// +// Memo memo; +// +// Operation operations<100>; +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class Transaction { + public Transaction () {} + private AccountID sourceAccount; + public AccountID getSourceAccount() { + return this.sourceAccount; + } + public void setSourceAccount(AccountID value) { + this.sourceAccount = value; + } + private Uint32 fee; + public Uint32 getFee() { + return this.fee; + } + public void setFee(Uint32 value) { + this.fee = value; + } + private SequenceNumber seqNum; + public SequenceNumber getSeqNum() { + return this.seqNum; + } + public void setSeqNum(SequenceNumber value) { + this.seqNum = value; + } + private TimeBounds timeBounds; + public TimeBounds getTimeBounds() { + return this.timeBounds; + } + public void setTimeBounds(TimeBounds value) { + this.timeBounds = value; + } + private Memo memo; + public Memo getMemo() { + return this.memo; + } + public void setMemo(Memo value) { + this.memo = value; + } + private Operation[] operations; + public Operation[] getOperations() { + return this.operations; + } + public void setOperations(Operation[] value) { + this.operations = value; + } + private TransactionExt ext; + public TransactionExt getExt() { + return this.ext; + } + public void setExt(TransactionExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, Transaction encodedTransaction) throws IOException{ + AccountID.encode(stream, encodedTransaction.sourceAccount); + Uint32.encode(stream, encodedTransaction.fee); + SequenceNumber.encode(stream, encodedTransaction.seqNum); + if (encodedTransaction.timeBounds != null) { + stream.writeInt(1); + TimeBounds.encode(stream, encodedTransaction.timeBounds); + } else { + stream.writeInt(0); + } + Memo.encode(stream, encodedTransaction.memo); + int operationssize = encodedTransaction.getOperations().length; + stream.writeInt(operationssize); + for (int i = 0; i < operationssize; i++) { + Operation.encode(stream, encodedTransaction.operations[i]); + } + TransactionExt.encode(stream, encodedTransaction.ext); + } + public static Transaction decode(XdrDataInputStream stream) throws IOException { + Transaction decodedTransaction = new Transaction(); + decodedTransaction.sourceAccount = AccountID.decode(stream); + decodedTransaction.fee = Uint32.decode(stream); + decodedTransaction.seqNum = SequenceNumber.decode(stream); + int timeBoundsPresent = stream.readInt(); + if (timeBoundsPresent != 0) { + decodedTransaction.timeBounds = TimeBounds.decode(stream); + } + decodedTransaction.memo = Memo.decode(stream); + int operationssize = stream.readInt(); + decodedTransaction.operations = new Operation[operationssize]; + for (int i = 0; i < operationssize; i++) { + decodedTransaction.operations[i] = Operation.decode(stream); + } + decodedTransaction.ext = TransactionExt.decode(stream); + return decodedTransaction; + } + + public static class TransactionExt { + public TransactionExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, TransactionExt encodedTransactionExt) throws IOException { + stream.writeInt(encodedTransactionExt.getDiscriminant().intValue()); + switch (encodedTransactionExt.getDiscriminant()) { + case 0: + break; + } + } + public static TransactionExt decode(XdrDataInputStream stream) throws IOException { + TransactionExt decodedTransactionExt = new TransactionExt(); + Integer discriminant = stream.readInt(); + decodedTransactionExt.setDiscriminant(discriminant); + switch (decodedTransactionExt.getDiscriminant()) { + case 0: + break; + } + return decodedTransactionExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionEnvelope.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionEnvelope.java new file mode 100644 index 0000000000..a8817ce860 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionEnvelope.java @@ -0,0 +1,54 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionEnvelope +// { +// Transaction tx; +// /* Each decorated signature is a signature over the SHA256 hash of +// * a TransactionSignaturePayload */ +// DecoratedSignature signatures<20>; +// }; + +// =========================================================================== +public class TransactionEnvelope { + public TransactionEnvelope () {} + private Transaction tx; + public Transaction getTx() { + return this.tx; + } + public void setTx(Transaction value) { + this.tx = value; + } + private DecoratedSignature[] signatures; + public DecoratedSignature[] getSignatures() { + return this.signatures; + } + public void setSignatures(DecoratedSignature[] value) { + this.signatures = value; + } + public static void encode(XdrDataOutputStream stream, TransactionEnvelope encodedTransactionEnvelope) throws IOException{ + Transaction.encode(stream, encodedTransactionEnvelope.tx); + int signaturessize = encodedTransactionEnvelope.getSignatures().length; + stream.writeInt(signaturessize); + for (int i = 0; i < signaturessize; i++) { + DecoratedSignature.encode(stream, encodedTransactionEnvelope.signatures[i]); + } + } + public static TransactionEnvelope decode(XdrDataInputStream stream) throws IOException { + TransactionEnvelope decodedTransactionEnvelope = new TransactionEnvelope(); + decodedTransactionEnvelope.tx = Transaction.decode(stream); + int signaturessize = stream.readInt(); + decodedTransactionEnvelope.signatures = new DecoratedSignature[signaturessize]; + for (int i = 0; i < signaturessize; i++) { + decodedTransactionEnvelope.signatures[i] = DecoratedSignature.decode(stream); + } + return decodedTransactionEnvelope; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionHistoryEntry.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionHistoryEntry.java new file mode 100644 index 0000000000..cbd1b81675 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionHistoryEntry.java @@ -0,0 +1,90 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionHistoryEntry +// { +// uint32 ledgerSeq; +// TransactionSet txSet; +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class TransactionHistoryEntry { + public TransactionHistoryEntry () {} + private Uint32 ledgerSeq; + public Uint32 getLedgerSeq() { + return this.ledgerSeq; + } + public void setLedgerSeq(Uint32 value) { + this.ledgerSeq = value; + } + private TransactionSet txSet; + public TransactionSet getTxSet() { + return this.txSet; + } + public void setTxSet(TransactionSet value) { + this.txSet = value; + } + private TransactionHistoryEntryExt ext; + public TransactionHistoryEntryExt getExt() { + return this.ext; + } + public void setExt(TransactionHistoryEntryExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, TransactionHistoryEntry encodedTransactionHistoryEntry) throws IOException{ + Uint32.encode(stream, encodedTransactionHistoryEntry.ledgerSeq); + TransactionSet.encode(stream, encodedTransactionHistoryEntry.txSet); + TransactionHistoryEntryExt.encode(stream, encodedTransactionHistoryEntry.ext); + } + public static TransactionHistoryEntry decode(XdrDataInputStream stream) throws IOException { + TransactionHistoryEntry decodedTransactionHistoryEntry = new TransactionHistoryEntry(); + decodedTransactionHistoryEntry.ledgerSeq = Uint32.decode(stream); + decodedTransactionHistoryEntry.txSet = TransactionSet.decode(stream); + decodedTransactionHistoryEntry.ext = TransactionHistoryEntryExt.decode(stream); + return decodedTransactionHistoryEntry; + } + + public static class TransactionHistoryEntryExt { + public TransactionHistoryEntryExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, TransactionHistoryEntryExt encodedTransactionHistoryEntryExt) throws IOException { + stream.writeInt(encodedTransactionHistoryEntryExt.getDiscriminant().intValue()); + switch (encodedTransactionHistoryEntryExt.getDiscriminant()) { + case 0: + break; + } + } + public static TransactionHistoryEntryExt decode(XdrDataInputStream stream) throws IOException { + TransactionHistoryEntryExt decodedTransactionHistoryEntryExt = new TransactionHistoryEntryExt(); + Integer discriminant = stream.readInt(); + decodedTransactionHistoryEntryExt.setDiscriminant(discriminant); + switch (decodedTransactionHistoryEntryExt.getDiscriminant()) { + case 0: + break; + } + return decodedTransactionHistoryEntryExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionHistoryResultEntry.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionHistoryResultEntry.java new file mode 100644 index 0000000000..532ea6eafb --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionHistoryResultEntry.java @@ -0,0 +1,90 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionHistoryResultEntry +// { +// uint32 ledgerSeq; +// TransactionResultSet txResultSet; +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class TransactionHistoryResultEntry { + public TransactionHistoryResultEntry () {} + private Uint32 ledgerSeq; + public Uint32 getLedgerSeq() { + return this.ledgerSeq; + } + public void setLedgerSeq(Uint32 value) { + this.ledgerSeq = value; + } + private TransactionResultSet txResultSet; + public TransactionResultSet getTxResultSet() { + return this.txResultSet; + } + public void setTxResultSet(TransactionResultSet value) { + this.txResultSet = value; + } + private TransactionHistoryResultEntryExt ext; + public TransactionHistoryResultEntryExt getExt() { + return this.ext; + } + public void setExt(TransactionHistoryResultEntryExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, TransactionHistoryResultEntry encodedTransactionHistoryResultEntry) throws IOException{ + Uint32.encode(stream, encodedTransactionHistoryResultEntry.ledgerSeq); + TransactionResultSet.encode(stream, encodedTransactionHistoryResultEntry.txResultSet); + TransactionHistoryResultEntryExt.encode(stream, encodedTransactionHistoryResultEntry.ext); + } + public static TransactionHistoryResultEntry decode(XdrDataInputStream stream) throws IOException { + TransactionHistoryResultEntry decodedTransactionHistoryResultEntry = new TransactionHistoryResultEntry(); + decodedTransactionHistoryResultEntry.ledgerSeq = Uint32.decode(stream); + decodedTransactionHistoryResultEntry.txResultSet = TransactionResultSet.decode(stream); + decodedTransactionHistoryResultEntry.ext = TransactionHistoryResultEntryExt.decode(stream); + return decodedTransactionHistoryResultEntry; + } + + public static class TransactionHistoryResultEntryExt { + public TransactionHistoryResultEntryExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, TransactionHistoryResultEntryExt encodedTransactionHistoryResultEntryExt) throws IOException { + stream.writeInt(encodedTransactionHistoryResultEntryExt.getDiscriminant().intValue()); + switch (encodedTransactionHistoryResultEntryExt.getDiscriminant()) { + case 0: + break; + } + } + public static TransactionHistoryResultEntryExt decode(XdrDataInputStream stream) throws IOException { + TransactionHistoryResultEntryExt decodedTransactionHistoryResultEntryExt = new TransactionHistoryResultEntryExt(); + Integer discriminant = stream.readInt(); + decodedTransactionHistoryResultEntryExt.setDiscriminant(discriminant); + switch (decodedTransactionHistoryResultEntryExt.getDiscriminant()) { + case 0: + break; + } + return decodedTransactionHistoryResultEntryExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionMeta.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionMeta.java new file mode 100644 index 0000000000..d71ef4d71a --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionMeta.java @@ -0,0 +1,76 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// union TransactionMeta switch (int v) +// { +// case 0: +// OperationMeta operations<>; +// case 1: +// TransactionMetaV1 v1; +// }; + +// =========================================================================== +public class TransactionMeta { + public TransactionMeta () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + private OperationMeta[] operations; + public OperationMeta[] getOperations() { + return this.operations; + } + public void setOperations(OperationMeta[] value) { + this.operations = value; + } + private TransactionMetaV1 v1; + public TransactionMetaV1 getV1() { + return this.v1; + } + public void setV1(TransactionMetaV1 value) { + this.v1 = value; + } + public static void encode(XdrDataOutputStream stream, TransactionMeta encodedTransactionMeta) throws IOException { + stream.writeInt(encodedTransactionMeta.getDiscriminant().intValue()); + switch (encodedTransactionMeta.getDiscriminant()) { + case 0: + int operationssize = encodedTransactionMeta.getOperations().length; + stream.writeInt(operationssize); + for (int i = 0; i < operationssize; i++) { + OperationMeta.encode(stream, encodedTransactionMeta.operations[i]); + } + break; + case 1: + TransactionMetaV1.encode(stream, encodedTransactionMeta.v1); + break; + } + } + public static TransactionMeta decode(XdrDataInputStream stream) throws IOException { + TransactionMeta decodedTransactionMeta = new TransactionMeta(); + Integer discriminant = stream.readInt(); + decodedTransactionMeta.setDiscriminant(discriminant); + switch (decodedTransactionMeta.getDiscriminant()) { + case 0: + int operationssize = stream.readInt(); + decodedTransactionMeta.operations = new OperationMeta[operationssize]; + for (int i = 0; i < operationssize; i++) { + decodedTransactionMeta.operations[i] = OperationMeta.decode(stream); + } + break; + case 1: + decodedTransactionMeta.v1 = TransactionMetaV1.decode(stream); + break; + } + return decodedTransactionMeta; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionMetaV1.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionMetaV1.java new file mode 100644 index 0000000000..b17916321b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionMetaV1.java @@ -0,0 +1,52 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionMetaV1 +// { +// LedgerEntryChanges txChanges; // tx level changes if any +// OperationMeta operations<>; // meta for each operation +// }; + +// =========================================================================== +public class TransactionMetaV1 { + public TransactionMetaV1 () {} + private LedgerEntryChanges txChanges; + public LedgerEntryChanges getTxChanges() { + return this.txChanges; + } + public void setTxChanges(LedgerEntryChanges value) { + this.txChanges = value; + } + private OperationMeta[] operations; + public OperationMeta[] getOperations() { + return this.operations; + } + public void setOperations(OperationMeta[] value) { + this.operations = value; + } + public static void encode(XdrDataOutputStream stream, TransactionMetaV1 encodedTransactionMetaV1) throws IOException{ + LedgerEntryChanges.encode(stream, encodedTransactionMetaV1.txChanges); + int operationssize = encodedTransactionMetaV1.getOperations().length; + stream.writeInt(operationssize); + for (int i = 0; i < operationssize; i++) { + OperationMeta.encode(stream, encodedTransactionMetaV1.operations[i]); + } + } + public static TransactionMetaV1 decode(XdrDataInputStream stream) throws IOException { + TransactionMetaV1 decodedTransactionMetaV1 = new TransactionMetaV1(); + decodedTransactionMetaV1.txChanges = LedgerEntryChanges.decode(stream); + int operationssize = stream.readInt(); + decodedTransactionMetaV1.operations = new OperationMeta[operationssize]; + for (int i = 0; i < operationssize; i++) { + decodedTransactionMetaV1.operations[i] = OperationMeta.decode(stream); + } + return decodedTransactionMetaV1; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionResult.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionResult.java new file mode 100644 index 0000000000..d2818025c3 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionResult.java @@ -0,0 +1,150 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionResult +// { +// int64 feeCharged; // actual fee charged for the transaction +// +// union switch (TransactionResultCode code) +// { +// case txSUCCESS: +// case txFAILED: +// OperationResult results<>; +// default: +// void; +// } +// result; +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// }; + +// =========================================================================== +public class TransactionResult { + public TransactionResult () {} + private Int64 feeCharged; + public Int64 getFeeCharged() { + return this.feeCharged; + } + public void setFeeCharged(Int64 value) { + this.feeCharged = value; + } + private TransactionResultResult result; + public TransactionResultResult getResult() { + return this.result; + } + public void setResult(TransactionResultResult value) { + this.result = value; + } + private TransactionResultExt ext; + public TransactionResultExt getExt() { + return this.ext; + } + public void setExt(TransactionResultExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, TransactionResult encodedTransactionResult) throws IOException{ + Int64.encode(stream, encodedTransactionResult.feeCharged); + TransactionResultResult.encode(stream, encodedTransactionResult.result); + TransactionResultExt.encode(stream, encodedTransactionResult.ext); + } + public static TransactionResult decode(XdrDataInputStream stream) throws IOException { + TransactionResult decodedTransactionResult = new TransactionResult(); + decodedTransactionResult.feeCharged = Int64.decode(stream); + decodedTransactionResult.result = TransactionResultResult.decode(stream); + decodedTransactionResult.ext = TransactionResultExt.decode(stream); + return decodedTransactionResult; + } + + public static class TransactionResultResult { + public TransactionResultResult () {} + TransactionResultCode code; + public TransactionResultCode getDiscriminant() { + return this.code; + } + public void setDiscriminant(TransactionResultCode value) { + this.code = value; + } + private OperationResult[] results; + public OperationResult[] getResults() { + return this.results; + } + public void setResults(OperationResult[] value) { + this.results = value; + } + public static void encode(XdrDataOutputStream stream, TransactionResultResult encodedTransactionResultResult) throws IOException { + stream.writeInt(encodedTransactionResultResult.getDiscriminant().getValue()); + switch (encodedTransactionResultResult.getDiscriminant()) { + case txSUCCESS: + case txFAILED: + int resultssize = encodedTransactionResultResult.getResults().length; + stream.writeInt(resultssize); + for (int i = 0; i < resultssize; i++) { + OperationResult.encode(stream, encodedTransactionResultResult.results[i]); + } + break; + default: + break; + } + } + public static TransactionResultResult decode(XdrDataInputStream stream) throws IOException { + TransactionResultResult decodedTransactionResultResult = new TransactionResultResult(); + TransactionResultCode discriminant = TransactionResultCode.decode(stream); + decodedTransactionResultResult.setDiscriminant(discriminant); + switch (decodedTransactionResultResult.getDiscriminant()) { + case txSUCCESS: + case txFAILED: + int resultssize = stream.readInt(); + decodedTransactionResultResult.results = new OperationResult[resultssize]; + for (int i = 0; i < resultssize; i++) { + decodedTransactionResultResult.results[i] = OperationResult.decode(stream); + } + break; + default: + break; + } + return decodedTransactionResultResult; + } + + } + public static class TransactionResultExt { + public TransactionResultExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, TransactionResultExt encodedTransactionResultExt) throws IOException { + stream.writeInt(encodedTransactionResultExt.getDiscriminant().intValue()); + switch (encodedTransactionResultExt.getDiscriminant()) { + case 0: + break; + } + } + public static TransactionResultExt decode(XdrDataInputStream stream) throws IOException { + TransactionResultExt decodedTransactionResultExt = new TransactionResultExt(); + Integer discriminant = stream.readInt(); + decodedTransactionResultExt.setDiscriminant(discriminant); + switch (decodedTransactionResultExt.getDiscriminant()) { + case 0: + break; + } + return decodedTransactionResultExt; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionResultCode.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionResultCode.java new file mode 100644 index 0000000000..916570c86d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionResultCode.java @@ -0,0 +1,78 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum TransactionResultCode +// { +// txSUCCESS = 0, // all operations succeeded +// +// txFAILED = -1, // one of the operations failed (none were applied) +// +// txTOO_EARLY = -2, // ledger closeTime before minTime +// txTOO_LATE = -3, // ledger closeTime after maxTime +// txMISSING_OPERATION = -4, // no operation was specified +// txBAD_SEQ = -5, // sequence number does not match source account +// +// txBAD_AUTH = -6, // too few valid signatures / wrong network +// txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve +// txNO_ACCOUNT = -8, // source account not found +// txINSUFFICIENT_FEE = -9, // fee is too small +// txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction +// txINTERNAL_ERROR = -11 // an unknown error occured +// }; + +// =========================================================================== +public enum TransactionResultCode { + txSUCCESS(0), + txFAILED(-1), + txTOO_EARLY(-2), + txTOO_LATE(-3), + txMISSING_OPERATION(-4), + txBAD_SEQ(-5), + txBAD_AUTH(-6), + txINSUFFICIENT_BALANCE(-7), + txNO_ACCOUNT(-8), + txINSUFFICIENT_FEE(-9), + txBAD_AUTH_EXTRA(-10), + txINTERNAL_ERROR(-11), + ; + private int mValue; + + TransactionResultCode(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static TransactionResultCode decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 0: return txSUCCESS; + case -1: return txFAILED; + case -2: return txTOO_EARLY; + case -3: return txTOO_LATE; + case -4: return txMISSING_OPERATION; + case -5: return txBAD_SEQ; + case -6: return txBAD_AUTH; + case -7: return txINSUFFICIENT_BALANCE; + case -8: return txNO_ACCOUNT; + case -9: return txINSUFFICIENT_FEE; + case -10: return txBAD_AUTH_EXTRA; + case -11: return txINTERNAL_ERROR; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, TransactionResultCode value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionResultPair.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionResultPair.java new file mode 100644 index 0000000000..f7b0183cf4 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionResultPair.java @@ -0,0 +1,44 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionResultPair +// { +// Hash transactionHash; +// TransactionResult result; // result for the transaction +// }; + +// =========================================================================== +public class TransactionResultPair { + public TransactionResultPair () {} + private Hash transactionHash; + public Hash getTransactionHash() { + return this.transactionHash; + } + public void setTransactionHash(Hash value) { + this.transactionHash = value; + } + private TransactionResult result; + public TransactionResult getResult() { + return this.result; + } + public void setResult(TransactionResult value) { + this.result = value; + } + public static void encode(XdrDataOutputStream stream, TransactionResultPair encodedTransactionResultPair) throws IOException{ + Hash.encode(stream, encodedTransactionResultPair.transactionHash); + TransactionResult.encode(stream, encodedTransactionResultPair.result); + } + public static TransactionResultPair decode(XdrDataInputStream stream) throws IOException { + TransactionResultPair decodedTransactionResultPair = new TransactionResultPair(); + decodedTransactionResultPair.transactionHash = Hash.decode(stream); + decodedTransactionResultPair.result = TransactionResult.decode(stream); + return decodedTransactionResultPair; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionResultSet.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionResultSet.java new file mode 100644 index 0000000000..87504913b5 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionResultSet.java @@ -0,0 +1,42 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionResultSet +// { +// TransactionResultPair results<>; +// }; + +// =========================================================================== +public class TransactionResultSet { + public TransactionResultSet () {} + private TransactionResultPair[] results; + public TransactionResultPair[] getResults() { + return this.results; + } + public void setResults(TransactionResultPair[] value) { + this.results = value; + } + public static void encode(XdrDataOutputStream stream, TransactionResultSet encodedTransactionResultSet) throws IOException{ + int resultssize = encodedTransactionResultSet.getResults().length; + stream.writeInt(resultssize); + for (int i = 0; i < resultssize; i++) { + TransactionResultPair.encode(stream, encodedTransactionResultSet.results[i]); + } + } + public static TransactionResultSet decode(XdrDataInputStream stream) throws IOException { + TransactionResultSet decodedTransactionResultSet = new TransactionResultSet(); + int resultssize = stream.readInt(); + decodedTransactionResultSet.results = new TransactionResultPair[resultssize]; + for (int i = 0; i < resultssize; i++) { + decodedTransactionResultSet.results[i] = TransactionResultPair.decode(stream); + } + return decodedTransactionResultSet; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionSet.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionSet.java new file mode 100644 index 0000000000..dbca78b553 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionSet.java @@ -0,0 +1,52 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionSet +// { +// Hash previousLedgerHash; +// TransactionEnvelope txs<>; +// }; + +// =========================================================================== +public class TransactionSet { + public TransactionSet () {} + private Hash previousLedgerHash; + public Hash getPreviousLedgerHash() { + return this.previousLedgerHash; + } + public void setPreviousLedgerHash(Hash value) { + this.previousLedgerHash = value; + } + private TransactionEnvelope[] txs; + public TransactionEnvelope[] getTxs() { + return this.txs; + } + public void setTxs(TransactionEnvelope[] value) { + this.txs = value; + } + public static void encode(XdrDataOutputStream stream, TransactionSet encodedTransactionSet) throws IOException{ + Hash.encode(stream, encodedTransactionSet.previousLedgerHash); + int txssize = encodedTransactionSet.getTxs().length; + stream.writeInt(txssize); + for (int i = 0; i < txssize; i++) { + TransactionEnvelope.encode(stream, encodedTransactionSet.txs[i]); + } + } + public static TransactionSet decode(XdrDataInputStream stream) throws IOException { + TransactionSet decodedTransactionSet = new TransactionSet(); + decodedTransactionSet.previousLedgerHash = Hash.decode(stream); + int txssize = stream.readInt(); + decodedTransactionSet.txs = new TransactionEnvelope[txssize]; + for (int i = 0; i < txssize; i++) { + decodedTransactionSet.txs[i] = TransactionEnvelope.decode(stream); + } + return decodedTransactionSet; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TransactionSignaturePayload.java b/app/src/main/java/org/stellar/sdk/xdr/TransactionSignaturePayload.java new file mode 100644 index 0000000000..4cb7d96f11 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TransactionSignaturePayload.java @@ -0,0 +1,88 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TransactionSignaturePayload +// { +// Hash networkId; +// union switch (EnvelopeType type) +// { +// case ENVELOPE_TYPE_TX: +// Transaction tx; +// /* All other values of type are invalid */ +// } +// taggedTransaction; +// }; + +// =========================================================================== +public class TransactionSignaturePayload { + public TransactionSignaturePayload () {} + private Hash networkId; + public Hash getNetworkId() { + return this.networkId; + } + public void setNetworkId(Hash value) { + this.networkId = value; + } + private TransactionSignaturePayloadTaggedTransaction taggedTransaction; + public TransactionSignaturePayloadTaggedTransaction getTaggedTransaction() { + return this.taggedTransaction; + } + public void setTaggedTransaction(TransactionSignaturePayloadTaggedTransaction value) { + this.taggedTransaction = value; + } + public static void encode(XdrDataOutputStream stream, TransactionSignaturePayload encodedTransactionSignaturePayload) throws IOException{ + Hash.encode(stream, encodedTransactionSignaturePayload.networkId); + TransactionSignaturePayloadTaggedTransaction.encode(stream, encodedTransactionSignaturePayload.taggedTransaction); + } + public static TransactionSignaturePayload decode(XdrDataInputStream stream) throws IOException { + TransactionSignaturePayload decodedTransactionSignaturePayload = new TransactionSignaturePayload(); + decodedTransactionSignaturePayload.networkId = Hash.decode(stream); + decodedTransactionSignaturePayload.taggedTransaction = TransactionSignaturePayloadTaggedTransaction.decode(stream); + return decodedTransactionSignaturePayload; + } + + public static class TransactionSignaturePayloadTaggedTransaction { + public TransactionSignaturePayloadTaggedTransaction () {} + EnvelopeType type; + public EnvelopeType getDiscriminant() { + return this.type; + } + public void setDiscriminant(EnvelopeType value) { + this.type = value; + } + private Transaction tx; + public Transaction getTx() { + return this.tx; + } + public void setTx(Transaction value) { + this.tx = value; + } + public static void encode(XdrDataOutputStream stream, TransactionSignaturePayloadTaggedTransaction encodedTransactionSignaturePayloadTaggedTransaction) throws IOException { + stream.writeInt(encodedTransactionSignaturePayloadTaggedTransaction.getDiscriminant().getValue()); + switch (encodedTransactionSignaturePayloadTaggedTransaction.getDiscriminant()) { + case ENVELOPE_TYPE_TX: + Transaction.encode(stream, encodedTransactionSignaturePayloadTaggedTransaction.tx); + break; + } + } + public static TransactionSignaturePayloadTaggedTransaction decode(XdrDataInputStream stream) throws IOException { + TransactionSignaturePayloadTaggedTransaction decodedTransactionSignaturePayloadTaggedTransaction = new TransactionSignaturePayloadTaggedTransaction(); + EnvelopeType discriminant = EnvelopeType.decode(stream); + decodedTransactionSignaturePayloadTaggedTransaction.setDiscriminant(discriminant); + switch (decodedTransactionSignaturePayloadTaggedTransaction.getDiscriminant()) { + case ENVELOPE_TYPE_TX: + decodedTransactionSignaturePayloadTaggedTransaction.tx = Transaction.decode(stream); + break; + } + return decodedTransactionSignaturePayloadTaggedTransaction; + } + + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TrustLineEntry.java b/app/src/main/java/org/stellar/sdk/xdr/TrustLineEntry.java new file mode 100644 index 0000000000..4d8a10ae4d --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TrustLineEntry.java @@ -0,0 +1,203 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// struct TrustLineEntry +// { +// AccountID accountID; // account this trustline belongs to +// Asset asset; // type of asset (with issuer) +// int64 balance; // how much of this asset the user has. +// // Asset defines the unit for this; +// +// int64 limit; // balance cannot be above this +// uint32 flags; // see TrustLineFlags +// +// // reserved for future use +// union switch (int v) +// { +// case 0: +// void; +// case 1: +// struct +// { +// Liabilities liabilities; +// +// union switch (int v) +// { +// case 0: +// void; +// } +// ext; +// } v1; +// } +// ext; +// }; + +// =========================================================================== +public class TrustLineEntry { + public TrustLineEntry () {} + private AccountID accountID; + public AccountID getAccountID() { + return this.accountID; + } + public void setAccountID(AccountID value) { + this.accountID = value; + } + private Asset asset; + public Asset getAsset() { + return this.asset; + } + public void setAsset(Asset value) { + this.asset = value; + } + private Int64 balance; + public Int64 getBalance() { + return this.balance; + } + public void setBalance(Int64 value) { + this.balance = value; + } + private Int64 limit; + public Int64 getLimit() { + return this.limit; + } + public void setLimit(Int64 value) { + this.limit = value; + } + private Uint32 flags; + public Uint32 getFlags() { + return this.flags; + } + public void setFlags(Uint32 value) { + this.flags = value; + } + private TrustLineEntryExt ext; + public TrustLineEntryExt getExt() { + return this.ext; + } + public void setExt(TrustLineEntryExt value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, TrustLineEntry encodedTrustLineEntry) throws IOException{ + AccountID.encode(stream, encodedTrustLineEntry.accountID); + Asset.encode(stream, encodedTrustLineEntry.asset); + Int64.encode(stream, encodedTrustLineEntry.balance); + Int64.encode(stream, encodedTrustLineEntry.limit); + Uint32.encode(stream, encodedTrustLineEntry.flags); + TrustLineEntryExt.encode(stream, encodedTrustLineEntry.ext); + } + public static TrustLineEntry decode(XdrDataInputStream stream) throws IOException { + TrustLineEntry decodedTrustLineEntry = new TrustLineEntry(); + decodedTrustLineEntry.accountID = AccountID.decode(stream); + decodedTrustLineEntry.asset = Asset.decode(stream); + decodedTrustLineEntry.balance = Int64.decode(stream); + decodedTrustLineEntry.limit = Int64.decode(stream); + decodedTrustLineEntry.flags = Uint32.decode(stream); + decodedTrustLineEntry.ext = TrustLineEntryExt.decode(stream); + return decodedTrustLineEntry; + } + + public static class TrustLineEntryExt { + public TrustLineEntryExt () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + private TrustLineEntryV1 v1; + public TrustLineEntryV1 getV1() { + return this.v1; + } + public void setV1(TrustLineEntryV1 value) { + this.v1 = value; + } + public static void encode(XdrDataOutputStream stream, TrustLineEntryExt encodedTrustLineEntryExt) throws IOException { + stream.writeInt(encodedTrustLineEntryExt.getDiscriminant().intValue()); + switch (encodedTrustLineEntryExt.getDiscriminant()) { + case 0: + break; + case 1: + TrustLineEntryV1.encode(stream, encodedTrustLineEntryExt.v1); + break; + } + } + public static TrustLineEntryExt decode(XdrDataInputStream stream) throws IOException { + TrustLineEntryExt decodedTrustLineEntryExt = new TrustLineEntryExt(); + Integer discriminant = stream.readInt(); + decodedTrustLineEntryExt.setDiscriminant(discriminant); + switch (decodedTrustLineEntryExt.getDiscriminant()) { + case 0: + break; + case 1: + decodedTrustLineEntryExt.v1 = TrustLineEntryV1.decode(stream); + break; + } + return decodedTrustLineEntryExt; + } + + public static class TrustLineEntryV1 { + public TrustLineEntryV1 () {} + private Liabilities liabilities; + public Liabilities getLiabilities() { + return this.liabilities; + } + public void setLiabilities(Liabilities value) { + this.liabilities = value; + } + private TrustLineEntryV1Ext ext; + public TrustLineEntryV1Ext getExt() { + return this.ext; + } + public void setExt(TrustLineEntryV1Ext value) { + this.ext = value; + } + public static void encode(XdrDataOutputStream stream, TrustLineEntryV1 encodedTrustLineEntryV1) throws IOException{ + Liabilities.encode(stream, encodedTrustLineEntryV1.liabilities); + TrustLineEntryV1Ext.encode(stream, encodedTrustLineEntryV1.ext); + } + public static TrustLineEntryV1 decode(XdrDataInputStream stream) throws IOException { + TrustLineEntryV1 decodedTrustLineEntryV1 = new TrustLineEntryV1(); + decodedTrustLineEntryV1.liabilities = Liabilities.decode(stream); + decodedTrustLineEntryV1.ext = TrustLineEntryV1Ext.decode(stream); + return decodedTrustLineEntryV1; + } + + public static class TrustLineEntryV1Ext { + public TrustLineEntryV1Ext () {} + Integer v; + public Integer getDiscriminant() { + return this.v; + } + public void setDiscriminant(Integer value) { + this.v = value; + } + public static void encode(XdrDataOutputStream stream, TrustLineEntryV1Ext encodedTrustLineEntryV1Ext) throws IOException { + stream.writeInt(encodedTrustLineEntryV1Ext.getDiscriminant().intValue()); + switch (encodedTrustLineEntryV1Ext.getDiscriminant()) { + case 0: + break; + } + } + public static TrustLineEntryV1Ext decode(XdrDataInputStream stream) throws IOException { + TrustLineEntryV1Ext decodedTrustLineEntryV1Ext = new TrustLineEntryV1Ext(); + Integer discriminant = stream.readInt(); + decodedTrustLineEntryV1Ext.setDiscriminant(discriminant); + switch (decodedTrustLineEntryV1Ext.getDiscriminant()) { + case 0: + break; + } + return decodedTrustLineEntryV1Ext; + } + + } + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/TrustLineFlags.java b/app/src/main/java/org/stellar/sdk/xdr/TrustLineFlags.java new file mode 100644 index 0000000000..bbc48f2c69 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/TrustLineFlags.java @@ -0,0 +1,43 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// enum TrustLineFlags +// { +// // issuer has authorized account to perform transactions with its credit +// AUTHORIZED_FLAG = 1 +// }; + +// =========================================================================== +public enum TrustLineFlags { + AUTHORIZED_FLAG(1), + ; + private int mValue; + + TrustLineFlags(int value) { + mValue = value; + } + + public int getValue() { + return mValue; + } + + static TrustLineFlags decode(XdrDataInputStream stream) throws IOException { + int value = stream.readInt(); + switch (value) { + case 1: return AUTHORIZED_FLAG; + default: + throw new RuntimeException("Unknown enum value: " + value); + } + } + + static void encode(XdrDataOutputStream stream, TrustLineFlags value) throws IOException { + stream.writeInt(value.getValue()); + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Uint256.java b/app/src/main/java/org/stellar/sdk/xdr/Uint256.java new file mode 100644 index 0000000000..5812ccb155 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Uint256.java @@ -0,0 +1,33 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef opaque uint256[32]; + +// =========================================================================== +public class Uint256 { + private byte[] uint256; + public byte[] getUint256() { + return this.uint256; + } + public void setUint256(byte[] value) { + this.uint256 = value; + } + public static void encode(XdrDataOutputStream stream, Uint256 encodedUint256) throws IOException { + int uint256size = encodedUint256.uint256.length; + stream.write(encodedUint256.getUint256(), 0, uint256size); + } + public static Uint256 decode(XdrDataInputStream stream) throws IOException { + Uint256 decodedUint256 = new Uint256(); + int uint256size = 32; + decodedUint256.uint256 = new byte[uint256size]; + stream.read(decodedUint256.uint256, 0, uint256size); + return decodedUint256; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Uint32.java b/app/src/main/java/org/stellar/sdk/xdr/Uint32.java new file mode 100644 index 0000000000..87b6544510 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Uint32.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef unsigned int uint32; + +// =========================================================================== +public class Uint32 { + private Integer uint32; + public Integer getUint32() { + return this.uint32; + } + public void setUint32(Integer value) { + this.uint32 = value; + } + public static void encode(XdrDataOutputStream stream, Uint32 encodedUint32) throws IOException { + stream.writeInt(encodedUint32.uint32); + } + public static Uint32 decode(XdrDataInputStream stream) throws IOException { + Uint32 decodedUint32 = new Uint32(); + decodedUint32.uint32 = stream.readInt(); + return decodedUint32; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Uint64.java b/app/src/main/java/org/stellar/sdk/xdr/Uint64.java new file mode 100644 index 0000000000..dd80d0eb0e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Uint64.java @@ -0,0 +1,30 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef unsigned hyper uint64; + +// =========================================================================== +public class Uint64 { + private Long uint64; + public Long getUint64() { + return this.uint64; + } + public void setUint64(Long value) { + this.uint64 = value; + } + public static void encode(XdrDataOutputStream stream, Uint64 encodedUint64) throws IOException { + stream.writeLong(encodedUint64.uint64); + } + public static Uint64 decode(XdrDataInputStream stream) throws IOException { + Uint64 decodedUint64 = new Uint64(); + decodedUint64.uint64 = stream.readLong(); + return decodedUint64; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/UpgradeType.java b/app/src/main/java/org/stellar/sdk/xdr/UpgradeType.java new file mode 100644 index 0000000000..08d7553f08 --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/UpgradeType.java @@ -0,0 +1,34 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef opaque UpgradeType<128>; + +// =========================================================================== +public class UpgradeType { + private byte[] UpgradeType; + public byte[] getUpgradeType() { + return this.UpgradeType; + } + public void setUpgradeType(byte[] value) { + this.UpgradeType = value; + } + public static void encode(XdrDataOutputStream stream, UpgradeType encodedUpgradeType) throws IOException { + int UpgradeTypesize = encodedUpgradeType.UpgradeType.length; + stream.writeInt(UpgradeTypesize); + stream.write(encodedUpgradeType.getUpgradeType(), 0, UpgradeTypesize); + } + public static UpgradeType decode(XdrDataInputStream stream) throws IOException { + UpgradeType decodedUpgradeType = new UpgradeType(); + int UpgradeTypesize = stream.readInt(); + decodedUpgradeType.UpgradeType = new byte[UpgradeTypesize]; + stream.read(decodedUpgradeType.UpgradeType, 0, UpgradeTypesize); + return decodedUpgradeType; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/Value.java b/app/src/main/java/org/stellar/sdk/xdr/Value.java new file mode 100644 index 0000000000..3ecebd3d5e --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/Value.java @@ -0,0 +1,34 @@ +// Automatically generated by xdrgen +// DO NOT EDIT or your changes may be overwritten + +package org.stellar.sdk.xdr; + + +import java.io.IOException; + +// === xdr source ============================================================ + +// typedef opaque Value<>; + +// =========================================================================== +public class Value { + private byte[] Value; + public byte[] getValue() { + return this.Value; + } + public void setValue(byte[] value) { + this.Value = value; + } + public static void encode(XdrDataOutputStream stream, Value encodedValue) throws IOException { + int Valuesize = encodedValue.Value.length; + stream.writeInt(Valuesize); + stream.write(encodedValue.getValue(), 0, Valuesize); + } + public static Value decode(XdrDataInputStream stream) throws IOException { + Value decodedValue = new Value(); + int Valuesize = stream.readInt(); + decodedValue.Value = new byte[Valuesize]; + stream.read(decodedValue.Value, 0, Valuesize); + return decodedValue; + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/XdrDataInputStream.java b/app/src/main/java/org/stellar/sdk/xdr/XdrDataInputStream.java new file mode 100644 index 0000000000..da75c84d9f --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/XdrDataInputStream.java @@ -0,0 +1,129 @@ +package org.stellar.sdk.xdr; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; + +public class XdrDataInputStream extends DataInputStream { + + // The underlying input stream + private final XdrInputStream mIn; + + /** + * Creates a XdrDataInputStream that uses the specified + * underlying InputStream. + * + * @param in the specified input stream + */ + public XdrDataInputStream(InputStream in) { + super(new XdrInputStream(in)); + mIn = (XdrInputStream) super.in; + } + + public String readString() throws IOException { + int l = readInt(); + byte[] bytes = new byte[l]; + read(bytes); + return new String(bytes, Charset.forName("UTF-8")); + } + + public int[] readIntArray() throws IOException { + int l = readInt(); + return readIntArray(l); + } + + private int[] readIntArray(int l) throws IOException { + int[] arr = new int[l]; + for (int i = 0; i < l; i++) { + arr[i] = readInt(); + } + return arr; + } + + public float[] readFloatArray() throws IOException { + int l = readInt(); + return readFloatArray(l); + } + + private float[] readFloatArray(int l) throws IOException { + float[] arr = new float[l]; + for (int i = 0; i < l; i++) { + arr[i] = readFloat(); + } + return arr; + } + + public double[] readDoubleArray() throws IOException { + int l = readInt(); + return readDoubleArray(l); + } + + private double[] readDoubleArray(int l) throws IOException { + double[] arr = new double[l]; + for (int i = 0; i < l; i++) { + arr[i] = readDouble(); + } + return arr; + } + + @Override + public int read() throws IOException { + return super.read(); + } + + /** + * Need to provide a custom impl of InputStream as DataInputStream's read methods + * are final and we need to keep track of the count for padding purposes. + */ + private static final class XdrInputStream extends InputStream { + + // The underlying input stream + private final InputStream mIn; + + // The amount of bytes read so far. + private int mCount; + + public XdrInputStream(InputStream in) { + mIn = in; + mCount = 0; + } + + @Override + public int read() throws IOException { + int read = mIn.read(); + if (read >= 0) { + mCount++; + } + return read; + } + + @Override + public int read(byte[] b) throws IOException { + return read(b, 0, b.length); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + int read = mIn.read(b, off, len); + mCount += read; + pad(); + return read; + } + + public void pad() throws IOException { + int pad = 0; + int mod = mCount % 4; + if (mod > 0) { + pad = 4-mod; + } + + while (pad-- > 0) { + int b = read(); + if (b != 0) { + throw new IOException("non-zero padding"); + } + } + } + } +} diff --git a/app/src/main/java/org/stellar/sdk/xdr/XdrDataOutputStream.java b/app/src/main/java/org/stellar/sdk/xdr/XdrDataOutputStream.java new file mode 100644 index 0000000000..672a01a76b --- /dev/null +++ b/app/src/main/java/org/stellar/sdk/xdr/XdrDataOutputStream.java @@ -0,0 +1,102 @@ +package org.stellar.sdk.xdr; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.Charset; + +public class XdrDataOutputStream extends DataOutputStream { + + private final XdrOutputStream mOut; + + public XdrDataOutputStream(OutputStream out) { + super(new XdrOutputStream(out)); + mOut = (XdrOutputStream) super.out; + } + + public void writeString(String s) throws IOException { + byte[] chars = s.getBytes(Charset.forName("UTF-8")); + writeInt(chars.length); + write(chars); + } + + public void writeIntArray(int[] a) throws IOException { + writeInt(a.length); + writeIntArray(a, a.length); + } + + private void writeIntArray(int[] a, int l) throws IOException { + for (int i = 0; i < l; i++) { + writeInt(a[i]); + } + } + + public void writeFloatArray(float[] a) throws IOException { + writeInt(a.length); + writeFloatArray(a, a.length); + } + + private void writeFloatArray(float[] a, int l) throws IOException { + for (int i = 0; i < l; i++) { + writeFloat(a[i]); + } + } + + public void writeDoubleArray(double[] a) throws IOException { + writeInt(a.length); + writeDoubleArray(a, a.length); + } + + private void writeDoubleArray(double[] a, int l) throws IOException { + for (int i = 0; i < l; i++) { + writeDouble(a[i]); + } + } + + private static final class XdrOutputStream extends OutputStream { + + private final OutputStream mOut; + + // Number of bytes written + private int mCount; + + public XdrOutputStream(OutputStream out) { + mOut = out; + mCount = 0; + } + + @Override + public void write(int b) throws IOException { + mOut.write(b); + // https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html#write(int): + // > The byte to be written is the eight low-order bits of the argument b. + // > The 24 high-order bits of b are ignored. + mCount++; + } + + @Override + public void write(byte[] b) throws IOException { + // https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html#write(byte[]): + // > The general contract for write(b) is that it should have exactly the same effect + // > as the call write(b, 0, b.length). + write(b, 0, b.length); + } + + public void write(byte[] b, int offset, int length) throws IOException { + mOut.write(b, offset, length); + mCount += length; + pad(); + } + + public void pad() throws IOException { + int pad = 0; + int mod = mCount % 4; + if (mod > 0) { + pad = 4-mod; + } + while (pad-- > 0) { + write(0); + } + } + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3c8bf2fa60..aa466fb7f7 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -160,7 +160,7 @@ Please wait while the payment is sent… Transaction has been successfully signed and sent to blockchain node. Wallet balance will be updated in a while - Try again. Failed to send transaction (%1$s) + Try again. Failed to send transaction (%s) Cannot sign transaction. Make sure you enter correct PIN2! Amount and fee exceed total wallet balance! diff --git a/tangemcard-common/build.gradle b/tangemcard-common/build.gradle index 15d24ac6d8..2bda781c11 100644 --- a/tangemcard-common/build.gradle +++ b/tangemcard-common/build.gradle @@ -5,6 +5,7 @@ dependencies { implementation 'com.madgag.spongycastle:core:1.56.0.0' implementation 'com.madgag.spongycastle:prov:1.56.0.0' + implementation 'net.i2p.crypto:eddsa:0.3.0' } diff --git a/tangemcard-common/src/main/java/com/tangem/tangemcard/reader/CardCrypto.java b/tangemcard-common/src/main/java/com/tangem/tangemcard/reader/CardCrypto.java index 04bc55e590..7cdea56f55 100644 --- a/tangemcard-common/src/main/java/com/tangem/tangemcard/reader/CardCrypto.java +++ b/tangemcard-common/src/main/java/com/tangem/tangemcard/reader/CardCrypto.java @@ -4,6 +4,15 @@ import com.tangem.tangemcard.util.Log; import com.tangem.tangemcard.util.PBKDF2; import com.tangem.tangemcard.util.Util; +import net.i2p.crypto.eddsa.EdDSAEngine; +import net.i2p.crypto.eddsa.EdDSAPrivateKey; +import net.i2p.crypto.eddsa.EdDSAPublicKey; +import net.i2p.crypto.eddsa.EdDSASecurityProvider; +import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable; +import net.i2p.crypto.eddsa.spec.EdDSAParameterSpec; +import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec; +import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec; + import org.spongycastle.asn1.ASN1EncodableVector; import org.spongycastle.asn1.ASN1Integer; import org.spongycastle.asn1.DERSequence; @@ -17,6 +26,7 @@ import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyFactory; +import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; @@ -39,122 +49,225 @@ import javax.crypto.spec.SecretKeySpec; public class CardCrypto { static { Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); + Security.addProvider(new EdDSASecurityProvider()); + } + + public enum Curve {secp256k1, ed25519} + + public static PublicKey LoadPublicKey(Curve curve, byte[] publicKeyArray) throws Exception { + if (publicKeyArray == null) throw new Exception("Public key not specified!"); + switch (curve) { + case secp256k1: { + ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); + KeyFactory factory = KeyFactory.getInstance("EC", "SC"); + + ECPoint p1 = spec.getCurve().decodePoint(publicKeyArray); + ECPublicKeySpec keySpec = new ECPublicKeySpec(p1, spec); + + return factory.generatePublic(keySpec); + } + case ed25519: { + EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519); + EdDSAPublicKeySpec pubKey = new EdDSAPublicKeySpec(publicKeyArray, spec); + return new EdDSAPublicKey(pubKey); + } + + default: + throw new Exception(curve.toString() + " not supported"); + } } public static PublicKey LoadPublicKey(byte[] publicKeyArray) throws Exception { - if( publicKeyArray==null ) throw new Exception("Public key not specified!"); - ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); - KeyFactory factory = KeyFactory.getInstance("EC", "SC"); + return LoadPublicKey(Curve.secp256k1, publicKeyArray); + } - ECPoint p1 = spec.getCurve().decodePoint(publicKeyArray); - ECPublicKeySpec keySpec = new ECPublicKeySpec(p1, spec); + public static boolean VerifySignature(Curve curve, byte[] publicKeyArray, byte[] data, byte[] signature) throws Exception { + switch (curve) { + case secp256k1: { + Signature signatureInstance = Signature.getInstance("SHA256withECDSA"); - return factory.generatePublic(keySpec); + PublicKey publicKey = LoadPublicKey(publicKeyArray); + signatureInstance.initVerify(publicKey); + signatureInstance.update(data); + + ASN1EncodableVector v = new ASN1EncodableVector(); + int size = signature.length / 2; + v.add(/* r */new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signature, 0, size)))); + v.add(/* s */new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signature, size, size * 2)))); + byte[] sigDer = new DERSequence(v).getEncoded(); + + return signatureInstance.verify(sigDer); + } + case ed25519: { + data = Util.calculateSHA512(data); + PublicKey publicKey = LoadPublicKey(curve, publicKeyArray); + EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519); + Signature signatureInstance = new EdDSAEngine(MessageDigest.getInstance(spec.getHashAlgorithm())); + signatureInstance.initVerify(publicKey); + + signatureInstance.update(data); + + return signatureInstance.verify(signature); + } + default: + throw new Exception(curve.toString() + " not supported"); + } } public static boolean VerifySignature(byte[] publicKeyArray, byte[] data, byte[] signature) throws Exception { - Signature signatureInstance = Signature.getInstance("SHA256withECDSA"); - PublicKey publicKey = LoadPublicKey(publicKeyArray); - signatureInstance.initVerify(publicKey); - signatureInstance.update(data); - - ASN1EncodableVector v = new ASN1EncodableVector(); - int size = signature.length / 2; - v.add(/*r*/new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signature, 0, size)))); - v.add(/*s*/new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signature, size, size * 2)))); - byte[] sigDer = new DERSequence(v).getEncoded(); - - return signatureInstance.verify(sigDer); + return VerifySignature(Curve.secp256k1, publicKeyArray, data, signature); } + public static boolean VerifySignature(String curveID, byte[] publicKeyArray, byte[] data, byte[] signature) throws Exception { + Curve curve; + try { + curve=Curve.valueOf(curveID); + } + catch (Exception e) + { + throw new Exception("Card EC curve ("+curveID+") isn't supported!"); + } + return VerifySignature(curve, publicKeyArray, data, signature); + } + + + public static byte[] Signature(Curve curve, byte[] privateKeyArray, byte[] data) throws Exception { + switch (curve) { + case secp256k1: { + ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); + KeyFactory factory = KeyFactory.getInstance("EC", "SC"); + + ECPrivateKeySpec keySpecP = new ECPrivateKeySpec(new BigInteger(1, privateKeyArray), spec); + + Signature signature = Signature.getInstance("SHA256withECDSA"); + + PrivateKey privateKey = factory.generatePrivate(keySpecP); + signature.initSign(privateKey); + signature.update(data); + byte[] enc = signature.sign(); + + if (enc[0] != 0x30) throw new Exception("bad encoding 1"); + if ((enc[1] & 0x80) != 0) throw new Exception("unsupported length encoding 1"); + if (enc[2] != 0x02) throw new Exception("bad encoding 2"); + if ((enc[3] & 0x80) != 0) throw new Exception("unsupported length encoding 2"); + int rLength = enc[3]; + + if (enc[4 + rLength] != 0x02) throw new Exception("bad encoding 3"); + if ((enc[5 + rLength] & 0x80) != 0) throw new Exception("unsupported length encoding 3"); + int sLength = enc[5 + rLength]; + + int sPos = 6 + rLength; + byte[] res = new byte[64]; + if (rLength <= 32) { + System.arraycopy(enc, 4, res, 32 - rLength, rLength); + rLength = 32; + } else if (rLength == 33 && enc[4] == 0) { + rLength--; + System.arraycopy(enc, 5, res, 0, rLength); + } else { + Log.e("cardCrypto", "r-length:" + String.valueOf(rLength)); + Log.e("cardCrypto", "s-length:" + String.valueOf(sLength)); + Log.e("cardCrypto", "enc:" + Util.bytesToHex(enc)); + throw new Exception("unsupported r-length - r-length:" + String.valueOf(rLength) + ",s-length:" + String.valueOf(sLength) + ",enc:" + Util.bytesToHex(enc)); + } + if (sLength <= 32) { + System.arraycopy(enc, sPos, res, rLength + 32 - sLength, sLength); + sLength = 32; + } else if (sLength == 33 && enc[sPos] == 0) { + System.arraycopy(enc, sPos + 1, res, rLength, sLength - 1); + } else { + Log.e("cardCrypto", "s-length:" + String.valueOf(sLength)); + Log.e("cardCrypto", "r-length:" + String.valueOf(rLength)); + Log.e("cardCrypto", "enc:" + Util.bytesToHex(enc)); + throw new Exception("unsupported s-length - r-length:" + String.valueOf(rLength) + ",s-length:" + String.valueOf(sLength) + ",enc:" + Util.bytesToHex(enc)); + } + + if (!VerifySignature(GeneratePublicKey(privateKeyArray), data, res)) { + throw new Exception("Signature self verify failed - r-length:" + String.valueOf(rLength) + ",s-length:" + String.valueOf(sLength) + ",enc:" + Util.bytesToHex(enc) + ",res:" + Util.bytesToHex(res)); + } + + return res; + } + case ed25519: { + data = Util.calculateSHA512(data); + EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519); + //Signature sgr = Signature.getInstance("EdDSA", "I2P"); + Signature signatureInstance = new EdDSAEngine(MessageDigest.getInstance(spec.getHashAlgorithm())); + + EdDSAPrivateKeySpec privateKeySpec = new EdDSAPrivateKeySpec(privateKeyArray, spec); + PrivateKey privateKey = new EdDSAPrivateKey(privateKeySpec); + + signatureInstance.initSign(privateKey); + signatureInstance.update(data); + + return signatureInstance.sign(); + } + default: + throw new Exception(curve.toString() + " not supported"); + } + } public static byte[] Signature(byte[] privateKeyArray, byte[] data) throws Exception { - ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); - KeyFactory factory = KeyFactory.getInstance("EC", "SC"); - - ECPrivateKeySpec keySpecP = new ECPrivateKeySpec(new BigInteger(1,privateKeyArray), spec); - - Signature signature = Signature.getInstance("SHA256withECDSA"); - - PrivateKey privateKey = factory.generatePrivate(keySpecP); - signature.initSign(privateKey); - signature.update(data); - byte[] enc = signature.sign(); - - if (enc[0] != 0x30) throw new Exception("bad encoding 1"); - if ((enc[1] & 0x80) != 0) throw new Exception("unsupported length encoding 1"); - if (enc[2] != 0x02) throw new Exception("bad encoding 2"); - if ((enc[3] & 0x80) != 0) throw new Exception("unsupported length encoding 2"); - int rLength = enc[3]; - - if (enc[4 + rLength] != 0x02) throw new Exception("bad encoding 3"); - if ((enc[5 + rLength] & 0x80) != 0) throw new Exception("unsupported length encoding 3"); - int sLength = enc[5 + rLength]; - - - int sPos = 6 + rLength; - byte[] res = new byte[64]; - if (rLength <= 32) { - System.arraycopy(enc, 4, res, 32-rLength, rLength); - rLength=32; - } else if (rLength == 33 && enc[4] == 0) { - rLength--; - System.arraycopy(enc, 5, res, 0, rLength); - } else { - Log.e("cardCrypto","r-length:" + String.valueOf(rLength)); - Log.e("cardCrypto","s-length:" + String.valueOf(sLength)); - Log.e("cardCrypto","enc:" + Util.bytesToHex(enc)); - throw new Exception("unsupported r-length - r-length:" + String.valueOf(rLength)+",s-length:" + String.valueOf(sLength)+",enc:" +Util.bytesToHex(enc)); - } - if (sLength <= 32) { - System.arraycopy(enc, sPos, res, rLength+32-sLength, sLength); - sLength=32; - } else if (sLength == 33 && enc[sPos] == 0) { - System.arraycopy(enc, sPos + 1, res, rLength, sLength - 1); - } else { - Log.e("cardCrypto","s-length:" + String.valueOf(sLength)); - Log.e("cardCrypto","r-length:" + String.valueOf(rLength)); - Log.e("cardCrypto","enc:" +Util.bytesToHex(enc)); - throw new Exception("unsupported s-length - r-length:" + String.valueOf(rLength)+",s-length:" + String.valueOf(sLength)+",enc:" +Util.bytesToHex(enc)); - } - - if(!VerifySignature(GeneratePublicKey(privateKeyArray), data, res)) - { - throw new Exception("Signature self verify failed - r-length:" + String.valueOf(rLength)+",s-length:" + String.valueOf(sLength)+",enc:" +Util.bytesToHex(enc)+",res:"+Util.bytesToHex(res)); - } - - return res; + return Signature(Curve.secp256k1, privateKeyArray, data); } - public static byte[] GeneratePublicKey(byte[] privateKeyArray) throws NoSuchProviderException, NoSuchAlgorithmException { - ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); + public static byte[] GeneratePublicKey(Curve curve, byte[] privateKeyArray) throws Exception { + switch (curve) { + case secp256k1: { + ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); + byte[] publicKeyArray = spec.getG().multiply(new BigInteger(1, privateKeyArray)).getEncoded(false); + + return publicKeyArray; + } + case ed25519: { + EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519); + + EdDSAPrivateKeySpec privateKeySpec = new EdDSAPrivateKeySpec(privateKeyArray, spec); + EdDSAPublicKeySpec publicKeySpec = new EdDSAPublicKeySpec(privateKeySpec.getA(), spec); + EdDSAPublicKey publicKey = new EdDSAPublicKey(publicKeySpec); + return publicKey.getAbyte(); + } + default: + throw new Exception(curve.toString() + " not supported"); + } + } - byte[] publicKeyArray = spec.getG().multiply(new BigInteger(1,privateKeyArray)).getEncoded(false); - - return publicKeyArray; + public static byte[] GeneratePublicKey(byte[] privateKeyArray) throws Exception { + return GeneratePublicKey(Curve.secp256k1, privateKeyArray); } /** - * Computes the PBKDF2 hash of a password. + * Computes the PBKDF2 hash of a password. * - * @param password the password to hash. - * @param salt the salt - * @param iterations the iteration count (slowness factor) - * @return the PBDKF2 hash of the password + * @param password the password to hash. + * @param salt the salt + * @param iterations the iteration count (slowness factor) + * @return the PBDKF2 hash of the password */ public static byte[] pbkdf2(byte[] password, byte[] salt, int iterations) throws InvalidKeyException { return PBKDF2.deriveKey(password, salt, iterations); } - public static byte[] Encrypt(byte[] key, byte[] data) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException - { - SecretKeySpec skeySpec = new SecretKeySpec(key, "AES/CBC/PKCS7PADDING"); - Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING", "BC"); - cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16])); - byte[] mEncryptedData = cipher.doFinal(data); - return mEncryptedData; + public static byte[] Encrypt(byte[] key, byte[] data, boolean UsePKCS7) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { + if (UsePKCS7) { + SecretKeySpec skeySpec = new SecretKeySpec(key, "AES/CBC/PKCS7PADDING"); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING", "SC"); + cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16])); + byte[] mEncryptedData = cipher.doFinal(data); + return mEncryptedData; + } else { + SecretKeySpec skeySpec = new SecretKeySpec(key, "AES/CBC/NOPADDING"); + Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING", "SC"); + cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16])); + byte[] mEncryptedData = cipher.doFinal(data); + return mEncryptedData; + } + } + + public static byte[] Encrypt(byte[] key, byte[] data) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { + return Encrypt(key, data, true); } public static byte[] Decrypt(byte[] key, byte[] data, boolean UsePKCS7) diff --git a/tangemcard-common/src/main/java/com/tangem/tangemcard/reader/CardProtocol.java b/tangemcard-common/src/main/java/com/tangem/tangemcard/reader/CardProtocol.java index d1251f2451..ee16f38539 100644 --- a/tangemcard-common/src/main/java/com/tangem/tangemcard/reader/CardProtocol.java +++ b/tangemcard-common/src/main/java/com/tangem/tangemcard/reader/CardProtocol.java @@ -707,12 +707,13 @@ public class CardProtocol { TLVList checkResult = run_CheckWallet(); if (checkResult == null) return; + TLV tlvCurveID = readResult.getTLV(TLV.Tag.TAG_CurveID); TLV tlvPublicKey = readResult.getTLV(TLV.Tag.TAG_Wallet_PublicKey); TLV tlvChallenge = checkResult.getTLV(TLV.Tag.TAG_Challenge); TLV tlvSalt = checkResult.getTLV(TLV.Tag.TAG_Salt); TLV tlvSignature = checkResult.getTLV(TLV.Tag.TAG_Signature); - if (tlvPublicKey == null || tlvChallenge == null || tlvSalt == null || tlvSignature == null) { + if (tlvCurveID == null || tlvPublicKey == null || tlvChallenge == null || tlvSalt == null || tlvSignature == null) { throw new TangemException("Not all data read, can't check signature!"); } @@ -721,7 +722,7 @@ public class CardProtocol { bs.write(tlvSalt.Value); byte[] dataArray = bs.toByteArray(); - if (CardCrypto.VerifySignature(tlvPublicKey.Value, dataArray, tlvSignature.Value)) { + if (CardCrypto.VerifySignature(tlvCurveID.getAsString(), tlvPublicKey.Value, dataArray, tlvSignature.Value)) { Log.i(logTag, "Signature verification OK"); mCard.setWalletPublicKeyValid(true); } else { diff --git a/tangemcard-common/src/main/java/com/tangem/tangemcard/tasks/CustomReadCardTask.java b/tangemcard-common/src/main/java/com/tangem/tangemcard/tasks/CustomReadCardTask.java index e807ed2f74..dc98568ce5 100644 --- a/tangemcard-common/src/main/java/com/tangem/tangemcard/tasks/CustomReadCardTask.java +++ b/tangemcard-common/src/main/java/com/tangem/tangemcard/tasks/CustomReadCardTask.java @@ -4,6 +4,7 @@ import com.tangem.tangemcard.data.external.CardDataSubstitutionProvider; import com.tangem.tangemcard.data.Manufacturer; import com.tangem.tangemcard.data.external.PINsProvider; import com.tangem.tangemcard.data.TangemCard; +import com.tangem.tangemcard.reader.CardCrypto; import com.tangem.tangemcard.reader.CardProtocol; import com.tangem.tangemcard.reader.NfcReader; import com.tangem.tangemcard.reader.TLV; @@ -20,6 +21,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; +import static com.tangem.tangemcard.reader.CardCrypto.Curve.secp256k1; + /** * Base class for card communication task */ @@ -245,15 +248,27 @@ public class CustomReadCardTask extends Thread { if (mCard.getStatus() == TangemCard.Status.Loaded) { TLV tlvPublicKey = protocol.getReadResult().getTLV(TLV.Tag.TAG_Wallet_PublicKey); + String curveID = protocol.getReadResult().getTLV(TLV.Tag.TAG_CurveID).getAsString(); - ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); - ECPoint p1 = spec.getCurve().decodePoint(tlvPublicKey.Value); + CardCrypto.Curve curve = CardCrypto.Curve.valueOf(curveID); + switch (curve) + { + case secp256k1: + ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); + ECPoint p1 = spec.getCurve().decodePoint(tlvPublicKey.Value); - byte pkUncompressed[] = p1.getEncoded(false); + byte pkUncompressed[] = p1.getEncoded(false); - byte pkCompresses[] = p1.getEncoded(true); - mCard.setWalletPublicKey(pkUncompressed); - mCard.setWalletPublicKeyRar(pkCompresses); + byte pkCompresses[] = p1.getEncoded(true); + mCard.setWalletPublicKey(pkUncompressed); + mCard.setWalletPublicKeyRar(pkCompresses); + break; + case ed25519: + mCard.setWalletPublicKey(tlvPublicKey.Value); + mCard.setWalletPublicKeyRar(tlvPublicKey.Value); + break; + + } mCard.setRemainingSignatures(protocol.getReadResult().getTagAsInt(TLV.Tag.TAG_RemainingSignatures)); From 6259944ff1b787067745af98570962694cfa816e Mon Sep 17 00:00:00 2001 From: Tangem Date: Tue, 18 Jun 2019 18:53:38 +0300 Subject: [PATCH 3/6] Updated on 2026-08-14 --- .../main/java/com/tangem/data/Blockchain.java | 6 +- .../tangem/data/network/ServerApiStellar.java | 16 ++- .../com/tangem/data/network/ServerURL.java | 3 +- .../tangem/data/network/StellarRequest.java | 12 ++ .../com/tangem/wallet/CoinEngineFactory.kt | 8 +- .../java/com/tangem/wallet/xlm/XlmData.java | 65 +++++++-- .../java/com/tangem/wallet/xlm/XlmEngine.java | 136 ++++++++++-------- 7 files changed, 161 insertions(+), 85 deletions(-) diff --git a/app/src/main/java/com/tangem/data/Blockchain.java b/app/src/main/java/com/tangem/data/Blockchain.java index 10990c3e19..4ab21c3565 100644 --- a/app/src/main/java/com/tangem/data/Blockchain.java +++ b/app/src/main/java/com/tangem/data/Blockchain.java @@ -22,9 +22,9 @@ public enum Blockchain { Binance("BINANCE", "BNB", 100000000.0, R.drawable.tangem2, "Binance"), BinanceTestNet("BINANCE/test", "BNB", 100000000.0, R.drawable.tangem2, "Binance Testnet"), Matic("MATIC", "MTX", 1.0, R.drawable.tangem2, "Matic"), - MaticTestNet("MATIC/test", "MTX", 1.0, R.drawable.tangem2, "Matic Testnet"); - Stellar("XLM", "XLM", R.drawable.ic_logo_stellar, "Stellar"), - StellarTestNet("XLM/test", "XLM", R.drawable.ic_logo_stellar, "Stellar Testnet"); + MaticTestNet("MATIC/test", "MTX", 1.0, R.drawable.tangem2, "Matic Testnet"), + Stellar("XLM", "XLM", 1000000.0, R.drawable.ic_logo_stellar, "Stellar"), + StellarTestNet("XLM/test", "XLM", 1000000.0, R.drawable.ic_logo_stellar, "Stellar Testnet"); Blockchain(String ID, String currency, double multiplier, int imageResource, String officialName) { mID = ID; diff --git a/app/src/main/java/com/tangem/data/network/ServerApiStellar.java b/app/src/main/java/com/tangem/data/network/ServerApiStellar.java index 2142d9ed8e..ea844facbc 100644 --- a/app/src/main/java/com/tangem/data/network/ServerApiStellar.java +++ b/app/src/main/java/com/tangem/data/network/ServerApiStellar.java @@ -2,9 +2,9 @@ package com.tangem.data.network; import com.tangem.App; import com.tangem.data.Blockchain; -import com.tangem.domain.wallet.TangemContext; import com.tangem.util.LOG; import com.tangem.wallet.R; +import com.tangem.wallet.TangemContext; import org.stellar.sdk.Network; import org.stellar.sdk.Server; @@ -19,7 +19,7 @@ import io.reactivex.schedulers.Schedulers; /** * Created by dvol on 7.01.2019. - * + *

* Request processor for Stellar Horizon Rest Api * Every request live cycle: * 1. In application create request and call {@link ServerApiStellar}.requestData(..) @@ -141,10 +141,16 @@ public class ServerApiStellar { private void doStellarRequest(TangemContext ctx, StellarRequest.Base stellarRequest) throws IOException { stellarRequest.setError(null); try { - if (ctx.getBlockchain() == Blockchain.StellarTestNet) { + Server server; + if (ctx.getBlockchain() == Blockchain.Stellar) { + Network.usePublicNetwork(); + server = new Server(ServerURL.API_STELLAR); + } else if (ctx.getBlockchain() == Blockchain.StellarTestNet) { Network.useTestNetwork(); + server = new Server(ServerURL.API_STELLAR_TESTNET); + } else { + throw new IOException("Wrong blockchain for ServerApiStellar"); } - Server server = new Server(ServerURL.API_STELLAR); try { LOG.e(TAG, "--- request " + stellarRequest.getClass().getSimpleName()); stellarRequest.process(server); @@ -155,7 +161,7 @@ public class ServerApiStellar { } } catch (Exception e) { e.printStackTrace(); - stellarRequest.setError(App.getInstance().getString(R.string.cannot_obtain_data_from_blockchain_communication_error)); + stellarRequest.setError(App.Companion.getInstance().getString(R.string.cannot_obtain_data_from_blockchain_communication_error)); throw e; } } 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 42bd4a288a..f563ca20eb 100644 --- a/app/src/main/java/com/tangem/data/network/ServerURL.java +++ b/app/src/main/java/com/tangem/data/network/ServerURL.java @@ -11,5 +11,6 @@ class ServerURL { static final String API_BINANCE = "https://dex.binance.org/"; static final String API_BINANCE_TESTNET = "https://testnet-dex.binance.org/"; static final String API_MATIC_TESTNET = "https://testnet2.matic.network"; - static final String API_STELLAR = "https://horizon-testnet.stellar.org"; + static final String API_STELLAR = "https://horizon.stellar.org/"; + static final String API_STELLAR_TESTNET = "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 index 88a50d8a6c..a7b66ce28e 100644 --- a/app/src/main/java/com/tangem/data/network/StellarRequest.java +++ b/app/src/main/java/com/tangem/data/network/StellarRequest.java @@ -5,6 +5,7 @@ import org.stellar.sdk.Server; import org.stellar.sdk.Transaction; import org.stellar.sdk.requests.ErrorResponse; import org.stellar.sdk.responses.AccountResponse; +import org.stellar.sdk.responses.LedgerResponse; import org.stellar.sdk.responses.SubmitTransactionResponse; import java.io.IOException; @@ -68,5 +69,16 @@ public class StellarRequest { } } + public static class Ledgers extends Base { + public LedgerResponse ledgerResponse; + + public Ledgers() {}; + + @Override + public void process(Server server) throws IOException { + int latestLedger = server.root().getCoreLatestLedger(); + ledgerResponse = server.ledgers().ledger(latestLedger); + } + } } \ No newline at end of file diff --git a/app/src/main/java/com/tangem/wallet/CoinEngineFactory.kt b/app/src/main/java/com/tangem/wallet/CoinEngineFactory.kt index 030e8ea07f..21bf4593cf 100644 --- a/app/src/main/java/com/tangem/wallet/CoinEngineFactory.kt +++ b/app/src/main/java/com/tangem/wallet/CoinEngineFactory.kt @@ -15,6 +15,7 @@ import com.tangem.wallet.matic.MaticTokenEngine import com.tangem.wallet.nftToken.NftTokenEngine import com.tangem.wallet.rsk.RskEngine import com.tangem.wallet.rsk.RskTokenEngine +import com.tangem.wallet.xlm.XlmEngine import com.tangem.wallet.xrp.XrpEngine /** @@ -43,6 +44,7 @@ object CoinEngineFactory { Blockchain.Ripple -> XrpEngine() Blockchain.Binance, Blockchain.BinanceTestNet -> BinanceEngine() Blockchain.Matic, Blockchain.MaticTestNet -> MaticTokenEngine() + Blockchain.StellarTestNet, Blockchain.Stellar -> XlmEngine() else -> null } } @@ -73,9 +75,9 @@ object CoinEngineFactory { else if (Blockchain.Binance == context.blockchain || Blockchain.BinanceTestNet == context.blockchain) BinanceEngine(context) else if (Blockchain.Matic == context.blockchain || Blockchain.MaticTestNet == context.blockchain) - MaticTokenEngine(context - - ) + MaticTokenEngine(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/wallet/xlm/XlmData.java b/app/src/main/java/com/tangem/wallet/xlm/XlmData.java index 32de8d2310..f8b0cd7e37 100644 --- a/app/src/main/java/com/tangem/wallet/xlm/XlmData.java +++ b/app/src/main/java/com/tangem/wallet/xlm/XlmData.java @@ -1,13 +1,17 @@ -package com.tangem.domain.wallet.xlm; +package com.tangem.wallet.xlm; import android.os.Bundle; import android.util.Log; -import com.tangem.domain.wallet.CoinData; -import com.tangem.domain.wallet.CoinEngine; +import com.tangem.wallet.CoinData; +import com.tangem.wallet.CoinEngine; +import org.bitcoinj.core.Coin; import org.stellar.sdk.KeyPair; import org.stellar.sdk.responses.AccountResponse; +import org.stellar.sdk.responses.LedgerResponse; + +import java.math.BigDecimal; /* * Created by dvol on 7.01.2019. @@ -16,8 +20,7 @@ import org.stellar.sdk.responses.AccountResponse; public class XlmData extends CoinData { - public static class AccountResponseEx extends AccountResponse - { + public static class AccountResponseEx extends AccountResponse { AccountResponseEx(String accountId, Long sequenceNumber) { super(KeyPair.fromAccountId(accountId), sequenceNumber); } @@ -26,7 +29,8 @@ public class XlmData extends CoinData { private CoinEngine.Amount balance = null; private Long sequenceNumber = 0L; - + private CoinEngine.Amount baseReserve = new CoinEngine.Amount("0.5", "XLM"); + private CoinEngine.Amount baseFee = new CoinEngine.Amount("0.00001", "XLM"); @Override public void clearInfo() { @@ -34,9 +38,20 @@ public class XlmData extends CoinData { balance = null; } - CoinEngine.Amount getBalanceXLM() { - return balance; + CoinEngine.Amount getBalance() { + if (balance != null) { + return new CoinEngine.Amount(balance.subtract(getReserve()), "XLM"); + } else { + return null; + } + } + CoinEngine.Amount getReserve() { + return new CoinEngine.Amount(baseReserve.multiply(BigDecimal.valueOf(2)), "XLM"); + } + + CoinEngine.Amount getBaseFee() { + return baseFee; } AccountResponse getAccountResponse() { @@ -44,7 +59,7 @@ public class XlmData extends CoinData { } void setAccountResponse(AccountResponse accountResponse) { - if( accountResponse.getBalances().length>0 ) { + if (accountResponse.getBalances().length > 0) { AccountResponse.Balance balanceResponse = accountResponse.getBalances()[0]; balance = new CoinEngine.Amount(balanceResponse.getBalance(), "XLM"); } @@ -52,6 +67,12 @@ public class XlmData extends CoinData { setBalanceReceived(true); } + void setLedgerResponse(LedgerResponse ledgerResponse) { + XlmEngine xlmEngine = new XlmEngine(); + baseReserve = xlmEngine.convertToAmount(new CoinEngine.InternalAmount(ledgerResponse.getBaseReserveInStroops(), "stroops")); + baseFee = xlmEngine.convertToAmount(new CoinEngine.InternalAmount(ledgerResponse.getBaseFeeInStroops(), "stroops")); + } + public void incSequenceNumber() { sequenceNumber++; } @@ -61,8 +82,7 @@ public class XlmData extends CoinData { super.loadFromBundle(B); if (B.containsKey("BalanceCurrency") && B.containsKey("BalanceDecimal")) { - String currency = B.getString("BalanceCurrency"); - balance = new CoinEngine.Amount(B.getString("BalanceDecimal"), currency); + balance = new CoinEngine.Amount(B.getString("BalanceDecimal"), B.getString("BalanceCurrency")); } else { balance = null; } @@ -72,6 +92,18 @@ public class XlmData extends CoinData { } else { sequenceNumber = 0L; } + + if (B.containsKey("BaseReserveCurrency") && B.containsKey("BaseReserveDecimal")) { + baseReserve = new CoinEngine.Amount(B.getString("BaseReserveDecimal"), B.getString("BaseReserveCurrency")); + } else { + baseReserve = new CoinEngine.Amount("0.5", "XLM"); + } + + if (B.containsKey("BaseFeeCurrency") && B.containsKey("BaseFeeDecimal")) { + baseFee = new CoinEngine.Amount(B.getString("BaseFeeDecimal"), B.getString("BaseFeeCurrency")); + } else { + baseFee = new CoinEngine.Amount("0.00001", "XLM"); + } } @Override @@ -87,10 +119,19 @@ public class XlmData extends CoinData { B.putLong("sequenceNumber", sequenceNumber); } + if (baseReserve != null) { + B.putString("BaseReserveCurrency", baseReserve.getCurrency()); + B.putString("BaseReserveDecimal", baseReserve.toValueString()); + } + + if (baseFee != null) { + B.putString("BaseFeeCurrency", baseFee.getCurrency()); + B.putString("BaseFeeDecimal", baseFee.toValueString()); + } + } catch (Exception e) { Log.e("Can't save to bundle ", e.getMessage()); } - } } diff --git a/app/src/main/java/com/tangem/wallet/xlm/XlmEngine.java b/app/src/main/java/com/tangem/wallet/xlm/XlmEngine.java index ceff856069..0e3d64c978 100644 --- a/app/src/main/java/com/tangem/wallet/xlm/XlmEngine.java +++ b/app/src/main/java/com/tangem/wallet/xlm/XlmEngine.java @@ -1,21 +1,21 @@ -package com.tangem.domain.wallet.xlm; +package com.tangem.wallet.xlm; import android.net.Uri; import android.text.InputFilter; import android.util.Log; +import com.tangem.card_common.data.TangemCard; +import com.tangem.card_common.tasks.SignTask; +import com.tangem.card_common.util.Util; 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.BalanceValidator; +import com.tangem.wallet.CoinData; +import com.tangem.wallet.CoinEngine; import com.tangem.wallet.R; +import com.tangem.wallet.TangemContext; import org.stellar.sdk.AssetTypeNative; import org.stellar.sdk.KeyPair; @@ -27,10 +27,10 @@ import java.io.IOException; import java.math.BigDecimal; /** -* Created by dvol on 7.01.2019. -* -* PS. To create and fill testnet account just open https://friendbot.stellar.org/?addr=XXX in browser -**/ + * Created by dvol on 7.01.2019. + *

+ * PS. To create and fill testnet account just open https://friendbot.stellar.org/?addr=XXX in browser + **/ public class XlmEngine extends CoinEngine { @@ -55,8 +55,7 @@ public class XlmEngine extends CoinEngine { } private static int getDecimals() { - //TODO - Is it's right? - return 8; + return 7; } @@ -75,7 +74,7 @@ public class XlmEngine extends CoinEngine { public String getBalanceHTML() { Amount balance = getBalance(); if (balance != null) { - return balance.toDescriptionString(getDecimals()); + return " " + balance.toDescriptionString(getDecimals()) + "
+ " + coinData.getReserve().toDescriptionString(getDecimals()) + " reserve"; } else { return ""; } @@ -96,14 +95,14 @@ public class XlmEngine extends CoinEngine { @Override public boolean isBalanceNotZero() { if (coinData == null) return false; - if (coinData.getBalanceXLM() == null) return false; - return coinData.getBalanceXLM().notZero(); + if (coinData.getBalance() == null) return false; + return coinData.getBalance().notZero(); } @Override public boolean hasBalanceInfo() { if (coinData == null) return false; - return coinData.getBalanceXLM() != null; + return coinData.getBalance() != null; } @@ -147,17 +146,17 @@ public class XlmEngine extends CoinEngine { } @Override - public Uri getShareWalletUriExplorer() { - return Uri.parse((ctx.getBlockchain() == Blockchain.Bitcoin ? "http://testnet.stellarchain.io/address/" : "http://testnet.stellarchain.io/address/") + ctx.getCoinData().getWallet()); + public Uri getWalletExplorerUri() { + return Uri.parse((ctx.getBlockchain() == Blockchain.Stellar ? "http://stellarchain.io/address/" : "http://testnet.stellarchain.io/address/") + ctx.getCoinData().getWallet()); } @Override public Uri getShareWalletUri() { //TODO - how to construct payment query intent for stellar? if (ctx.getCard().getDenomination() != null) { - return Uri.parse("stellar:" + ctx.getCoinData().getWallet() + "?amount=" + convertToAmount(convertToInternalAmount(ctx.getCard().getDenomination())).toValueString()); + return Uri.parse(ctx.getCoinData().getWallet() + "?amount=" + convertToAmount(convertToInternalAmount(ctx.getCard().getDenomination())).toValueString()); } else { - return Uri.parse("stellar:" + ctx.getCoinData().getWallet()); + return Uri.parse(ctx.getCoinData().getWallet()); } } @@ -169,7 +168,7 @@ public class XlmEngine extends CoinEngine { @Override public boolean checkNewTransactionAmount(Amount amount) { if (coinData == null) return false; - if (amount.compareTo(coinData.getBalanceXLM()) > 0) { + if (amount.compareTo(coinData.getBalance()) > 0) { return false; } return true; @@ -190,10 +189,10 @@ public class XlmEngine extends CoinEngine { if (feeValue.isZero() || amountValue.isZero()) return false; - if (isIncludeFee && (amountValue.compareTo(coinData.getBalanceXLM()) > 0 || amountValue.compareTo(feeValue) < 0)) + if (isIncludeFee && (amountValue.compareTo(coinData.getBalance()) > 0 || amountValue.compareTo(feeValue) < 0)) return false; - if (!isIncludeFee && amountValue.add(feeValue).compareTo(coinData.getBalanceXLM()) > 0) + if (!isIncludeFee && amountValue.add(feeValue).compareTo(coinData.getBalance()) > 0) return false; return true; @@ -228,7 +227,7 @@ public class XlmEngine extends CoinEngine { balanceValidator.setScore(100); balanceValidator.setFirstLine("Verified balance"); balanceValidator.setSecondLine("Balance confirmed in blockchain"); - if (coinData.getBalanceXLM().isZero()) { + if (coinData.getBalance().isZero()) { balanceValidator.setFirstLine("Empty wallet"); balanceValidator.setSecondLine(""); } @@ -243,7 +242,7 @@ public class XlmEngine extends CoinEngine { // return; // } - if ((ctx.getCard().getOfflineBalance() != null) && !coinData.isBalanceReceived() && (ctx.getCard().getRemainingSignatures() == ctx.getCard().getMaxSignatures()) && coinData.getBalanceXLM().notZero()) { + if ((ctx.getCard().getOfflineBalance() != null) && !coinData.isBalanceReceived() && (ctx.getCard().getRemainingSignatures() == ctx.getCard().getMaxSignatures()) && coinData.getBalance().notZero()) { balanceValidator.setScore(80); balanceValidator.setFirstLine("Verified offline balance"); balanceValidator.setSecondLine("Can't obtain balance from blockchain. Restore internet connection to be more confident. "); @@ -274,7 +273,7 @@ public class XlmEngine extends CoinEngine { @Override public Amount getBalance() { if (!hasBalanceInfo()) return null; - return coinData.getBalanceXLM(); + return coinData.getBalance(); } @Override @@ -349,22 +348,20 @@ public class XlmEngine extends CoinEngine { @Override - public SignTask.PaymentToSign constructPayment(Amount amountValue, Amount feeValue, boolean IncFee, String targetAddress) throws Exception { + public SignTask.TransactionToSign constructTransaction(Amount amountValue, Amount feeValue, boolean IncFee, String targetAddress) throws Exception { checkBlockchainDataExists(); - if( IncFee ) - { - amountValue=new Amount(amountValue.subtract(feeValue), amountValue.getCurrency()); + if (IncFee) { + amountValue = new Amount(amountValue.subtract(feeValue), amountValue.getCurrency()); } - TransactionEx transaction = TransactionEx.buildEx(60, coinData.getAccountResponse(), new PaymentOperation.Builder(KeyPair.fromAccountId(targetAddress), new AssetTypeNative(), amountValue.toValueString()).build()); + TransactionEx transaction = TransactionEx.buildEx(60, coinData.getAccountResponse(), new PaymentOperation.Builder(KeyPair.fromAccountId(targetAddress), new AssetTypeNative(), amountValue.toValueString()).build()); - if( transaction.getFee()!=convertToInternalAmount(feeValue).intValueExact() ) - { + if (transaction.getFee() != convertToInternalAmount(feeValue).intValueExact()) { throw new Exception("Invalid fee!"); } - return new SignTask.PaymentToSign() { + return new SignTask.TransactionToSign() { @Override public boolean isSigningMethodSupported(TangemCard.SigningMethod signingMethod) { @@ -399,7 +396,7 @@ public class XlmEngine extends CoinEngine { transaction.setSign(signFromCard); byte[] txForSend = transaction.toEnvelopeXdrBase64().getBytes(); - notifyOnNeedSendPayment(txForSend); + notifyOnNeedSendTransaction(txForSend); return txForSend; } }; @@ -413,18 +410,30 @@ public class XlmEngine extends CoinEngine { @Override public void onSuccess(StellarRequest.Base request) { Log.i(TAG, "onSuccess: " + request.getClass().getSimpleName()); - if (!StellarRequest.Balance.class.isInstance(request)) { + + if (request instanceof StellarRequest.Balance) { + StellarRequest.Balance balanceRequest = (StellarRequest.Balance) request; + + coinData.setAccountResponse(balanceRequest.accountResponse); + + if (serverApi.isRequestsSequenceCompleted()) { + blockchainRequestsCallbacks.onComplete(!ctx.hasError()); + } else { + blockchainRequestsCallbacks.onProgress(); + } + } else if (request instanceof StellarRequest.Ledgers) { + StellarRequest.Ledgers ledgersRequest = (StellarRequest.Ledgers) request; + + coinData.setLedgerResponse(ledgersRequest.ledgerResponse); + + if (serverApi.isRequestsSequenceCompleted()) { + blockchainRequestsCallbacks.onComplete(!ctx.hasError()); + } else { + blockchainRequestsCallbacks.onProgress(); + } + } else { ctx.setError("Invalid request logic"); blockchainRequestsCallbacks.onComplete(false); - return; - } - StellarRequest.Balance balanceRequest = (StellarRequest.Balance) request; - - coinData.setAccountResponse(balanceRequest.accountResponse); - if (serverApi.isRequestsSequenceCompleted()) { - blockchainRequestsCallbacks.onComplete(!ctx.hasError()); - } else { - blockchainRequestsCallbacks.onProgress(); } } @@ -444,19 +453,13 @@ public class XlmEngine extends CoinEngine { serverApi.setListener(listener); serverApi.requestData(ctx, new StellarRequest.Balance(coinData.getWallet())); + serverApi.requestData(ctx, new StellarRequest.Ledgers()); } @Override public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) throws Exception { - final int calcSize = 0; - // todo - take BASE_FEE from last leger - 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()); + // TODO: get fee stats? + coinData.minFee = coinData.normalFee = coinData.maxFee = coinData.getBaseFee(); blockchainRequestsCallbacks.onComplete(true); } @@ -468,19 +471,20 @@ public class XlmEngine extends CoinEngine { @Override public void onSuccess(StellarRequest.Base request) { try { - if (!StellarRequest.SubmitTransaction.class.isInstance(request)) throw new Exception("Invalid request logic"); + 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 { - if( submitTransactionRequest.response.getExtras()!=null && submitTransactionRequest.response.getExtras().getResultCodes()!=null ) { + if (submitTransactionRequest.response.getExtras() != null && submitTransactionRequest.response.getExtras().getResultCodes() != null) { String trResult = submitTransactionRequest.response.getExtras().getResultCodes().getTransactionResultCode(); - if( submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes()!=null && submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes().size()>0 ) { - trResult+="/"+submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes().get(0); + if (submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes() != null && submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes().size() > 0) { + trResult += "/" + submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes().get(0); } ctx.setError(trResult); - }else{ + } else { ctx.setError("transaction failed"); } blockchainRequestsCallbacks.onComplete(false); @@ -511,4 +515,14 @@ public class XlmEngine extends CoinEngine { } + public boolean needMultipleLinesForBalance() { + return true; + } + + public boolean allowSelectFeeLevel() { + return false; + } + + public int pendingTransactionTimeoutInSeconds() { return 10; } + } \ No newline at end of file From 03e476c94bb3e4069d4fa9b3cdd9358583709686 Mon Sep 17 00:00:00 2001 From: Tangem Date: Thu, 20 Jun 2019 14:42:07 +0300 Subject: [PATCH 4/6] Updated on 2026-08-14 --- app/src/main/java/com/tangem/wallet/xrp/XrpEngine.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/tangem/wallet/xrp/XrpEngine.java b/app/src/main/java/com/tangem/wallet/xrp/XrpEngine.java index ebc9b0d847..fbf7fe16d3 100644 --- a/app/src/main/java/com/tangem/wallet/xrp/XrpEngine.java +++ b/app/src/main/java/com/tangem/wallet/xrp/XrpEngine.java @@ -68,7 +68,7 @@ public class XrpEngine extends CoinEngine { public String getBalanceHTML() { Amount balance = getBalance(); if (balance != null) { - return " " + balance.toDescriptionString(getDecimals()) + "
+ " + convertToAmount(coinData.getReserveInInternalUnits()).toDescriptionString(getDecimals()) + " reserve"; + return " " + balance.toDescriptionString(getDecimals()) + "
+ " + convertToAmount(coinData.getReserveInInternalUnits()).toDescriptionString(getDecimals()) + " reserve"; } else { return ""; } From 2849b91f6fcb0b98f19c347d99309208313c56c6 Mon Sep 17 00:00:00 2001 From: Tangem Date: Thu, 20 Jun 2019 14:42:31 +0300 Subject: [PATCH 5/6] Updated on 2026-08-14 --- app/src/main/java/com/tangem/wallet/token/TokenEngine.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/tangem/wallet/token/TokenEngine.java b/app/src/main/java/com/tangem/wallet/token/TokenEngine.java index 76ee75f8c5..ab4d60aab0 100644 --- a/app/src/main/java/com/tangem/wallet/token/TokenEngine.java +++ b/app/src/main/java/com/tangem/wallet/token/TokenEngine.java @@ -97,7 +97,7 @@ public class TokenEngine extends CoinEngine { public String getBalanceHTML() { if (hasBalanceInfo()) { try { - return " " + convertToAmount(coinData.getBalanceInInternalUnits()).toDescriptionString(getTokenDecimals()) + "
+ " + convertToAmount(coinData.getBalanceAlterInInternalUnits()).toDescriptionString(getChainDecimals()) + " for fee"; + return " " + convertToAmount(coinData.getBalanceInInternalUnits()).toDescriptionString(getTokenDecimals()) + "
+ " + convertToAmount(coinData.getBalanceAlterInInternalUnits()).toDescriptionString(getChainDecimals()) + " for fee"; } catch (Exception e) { e.printStackTrace(); return ""; From 478519331cd822ff03dd0314eb6a42bea60cce0e Mon Sep 17 00:00:00 2001 From: Tangem Date: Thu, 20 Jun 2019 17:34:43 +0300 Subject: [PATCH 6/6] Updated on 2026-08-14 --- .../com/tangem/ui/PrepareTransactionActivity.kt | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/app/src/tangemAccess/java/com/tangem/ui/PrepareTransactionActivity.kt b/app/src/tangemAccess/java/com/tangem/ui/PrepareTransactionActivity.kt index cd0e3491e1..f363dd302c 100644 --- a/app/src/tangemAccess/java/com/tangem/ui/PrepareTransactionActivity.kt +++ b/app/src/tangemAccess/java/com/tangem/ui/PrepareTransactionActivity.kt @@ -152,11 +152,23 @@ class PrepareTransactionActivity : AppCompatActivity(), NfcAdapter.ReaderCallbac if (code.contains("ethereum:")) { val tmp = code.split("ethereum:".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() code = tmp[1] - } else if (code.contains("blockchain:")) { + } else if (code.contains("blockchain:")) { //TODO: is this needed? val tmp = code.split("blockchain:".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() code = tmp[1] } } + Blockchain.Litecoin -> { + if (code.contains("litecoin:")) { + val tmp = code.split("litecoin:".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + code = tmp[1] + } + } + Blockchain.Ripple -> { + if (code.contains("ripple:")) { + val tmp = code.split("ripple:".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + code = tmp[1] + } + } else -> { } }