From 22a9ab8e3b737a200cd94f573bc448e43bd69a69 Mon Sep 17 00:00:00 2001
From: Amitai Efrati See {@link KinAccount#sendTransactionSync(Transaction)} for possibles errors Note: This method accesses the network, and should not be called on the android main thread. Note: This method accesses the network, and should not be called on the android main thread. See {@link KinAccount#sendTransactionSync(Transaction)} for possibles errors Note: This method accesses the network, and should not be called on the android main thread. Note: This method accesses the network, and should not be called on the android main thread. See {@link KinAccount#getTransactionBuilderSync()} for possibles errors Note: This method accesses the network, and should not be called on the android main thread. See {@link KinAccount#getAggregatedBalanceSync()} for possibles errors Note: This method accesses the network, and should not be called on the android main thread. See {@link KinAccount#getControlledAccountsSync()} for possibles errors Note: This method accesses the network, and should not be called on the android main thread. See {@link KinAccount#getAccountDataSync()} for possibles errors Note: This method accesses the network, and should not be called on the android main thread. See {@link KinAccount#getTransactionBuilderSync()} for possibles errors Note: This method accesses the network, and should not be called on the android main thread. See {@link KinAccount#sendTransactionSync(Transaction)} for possibles errors Note: This method accesses the network, and should not be called on the android main thread. Note: This method accesses the network, and should not be called on the android main thread. Note: This method accesses the network, and should not be called on the android main thread. See {@link ControlledAccount} for more information on a controlled account See {@link KinAccount#getAggregatedBalanceSync()} for possibles errors See {@link ControlledAccount} for more information on a controlled account See {@link KinAccount#getControlledAccountsSync()} for possibles errorsGET /accounts/{account}/aggregate_balance
+ *
+ * @param account Account to fetch
+ * @see Account Details
+ */
+ public AggregatedBalanceResponse aggregateBalance(KeyPair account) throws IOException {
+ this.setSegments("accounts", account.getAccountId(), "aggregate_balance");
+ return this.aggregateBalance(this.buildUri());
+ }
+
+ /**
+ * Requests specific uri and returns {@link AggregatedBalanceResponse}. This method is helpful for
+ * getting the links.
+ */
+ public AggregatedBalanceResponse aggregateBalance(URI uri) throws IOException {
+ TypeToken type = new TypeTokenGET /accounts/{account}/controlled_balances
+ *
+ * @param account Account to fetch
+ * @see Account Details
+ */
+ public ControlledAccountsResponse controlledAccounts(KeyPair account) throws IOException {
+ this.setSegments("accounts", account.getAccountId(), "controlled_balances");
+ return this.controlledAccounts(this.buildUri());
+ }
+
+ /**
+ * Requests specific uri and returns {@link ControlledAccountsResponse}. This method is helpful for
+ * getting the links.
+ */
+ public ControlledAccountsResponse controlledAccounts(URI uri) throws IOException {
+ TypeToken type = new TypeTokenuri and returns {@link Page} of {@link AccountResponse}.
* This method is helpful for getting the next set of results.
@@ -97,4 +149,5 @@ public AccountsRequestBuilder order(Order direction) {
super.order(direction);
return this;
}
+
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/AccountResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/AccountResponse.java
index efc8c831..8851ecbb 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/AccountResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/AccountResponse.java
@@ -3,6 +3,7 @@
import static kin.base.Util.checkNotNull;
import com.google.gson.annotations.SerializedName;
+import java.util.Map;
import kin.base.Asset;
import kin.base.AssetTypeNative;
import kin.base.KeyPair;
@@ -38,6 +39,8 @@ public class AccountResponse extends Response implements TransactionBuilderAccou
private Signer[] signers;
@SerializedName("_links")
private Links links;
+ @SerializedName("data")
+ private Map> getControlledAccounts() {
+ return new Request<>(new Callable
>() {
+ @Override
+ public List
>} List
> getControlledAccounts();
+
+ /**
+ * Get the current list of controlled accounts
+ *
GET /accounts/{account}/aggregate_balance
*
- * @param account Account to fetch
- * @see Account Details
+ * @param account Account to fetch the aggregated balance for.
*/
public AggregatedBalanceResponse aggregateBalance(KeyPair account) throws IOException {
this.setSegments("accounts", account.getAccountId(), "aggregate_balance");
@@ -67,13 +64,11 @@ public AggregatedBalanceResponse aggregateBalance(URI uri) throws IOException {
return responseHandler.handleGetRequest(uri);
}
- // TODO: 2019-05-29 maybe blockchain need to add the description in their docs.
-
+ // TODO: 2019-05-29 we may need a url for the method description, need to check if blockchain team can even add it.
/**
* Requests GET /accounts/{account}/controlled_balances
*
- * @param account Account to fetch
- * @see Account Details
+ * @param account the account in which we get all his controlled accounts
*/
public ControlledAccountsResponse controlledAccounts(KeyPair account) throws IOException {
this.setSegments("accounts", account.getAccountId(), "controlled_balances");
From 6fc037751e22eb2bd68b990041c315075b8dc08f Mon Sep 17 00:00:00 2001
From: Amitai Efrati >} List
Transaction instance from previously build TransactionEnvelope
+ *
+ * @param transactionEnvelope a Base-64 encoded TransactionEnvelope
+ */
public static Transaction decodeTransaction(String transactionEnvelope) throws DecodeTransactionException {
try {
kin.base.Transaction transaction = kin.base.Transaction.fromEnvelopeXdr(transactionEnvelope);
- TransactionId id = new TransactionIdImpl(Utils.byteArrayToHex(transaction.hash()));
- return new Transaction(id, transaction);
+ return new Transaction(transaction);
} catch (IOException e) {
throw new DecodeTransactionException(e.getMessage(), e.getCause());
}
@@ -35,6 +33,9 @@ public KeyPair getSource() {
return baseTransaction.getSourceAccount();
}
+ /**
+ * Returns fee paid for transaction in kin base unit (1 base unit = 0.00001 KIN).
+ */
public int getFee() {
return baseTransaction.getFee();
}
@@ -43,23 +44,37 @@ public Memo getMemo() {
return baseTransaction.getMemo();
}
+ /**
+ * return The transaction hash
+ */
public TransactionId getId() {
- return id;
+ return new TransactionIdImpl(Utils.byteArrayToHex(baseTransaction.hash()));
}
kin.base.Transaction getBaseTransaction() {
return baseTransaction;
}
+ /**
+ * see {@link WhitelistableTransaction} for more information on a whitelistable transaction
See {@link KinAccount#sendTransactionSync(Transaction)} for possibles errors
+ *See {@link KinAccount#sendTransactionSync(RawTransaction)} for possibles errors
* @param transaction is the transaction object to send. * @return {@code RequestTransactionEnvelope
*/
- public static Transaction decodeTransaction(String transactionEnvelope) throws DecodeTransactionException {
+ public static RawTransaction decodeTransaction(String transactionEnvelope) throws DecodeTransactionException {
try {
kin.base.Transaction transaction = kin.base.Transaction.fromEnvelopeXdr(transactionEnvelope);
- return new Transaction(transaction);
+ return new RawTransaction(transaction);
} catch (IOException e) {
throw new DecodeTransactionException(e.getMessage(), e.getCause());
}
}
- public KeyPair source() {
- return baseTransaction.getSourceAccount();
- }
-
- /**
- * Returns fee paid for transaction in kin base unit (1 base unit = 0.00001 KIN).
- */
- public int fee() {
- return baseTransaction.getFee();
- }
-
public Memo memo() {
- return baseTransaction.getMemo();
- }
-
- /**
- * return The transaction hash
- */
- public TransactionId id() {
- return new TransactionIdImpl(Utils.byteArrayToHex(baseTransaction.hash()));
- }
-
- kin.base.Transaction baseTransaction() {
- return baseTransaction;
+ return baseTransaction().getMemo();
}
/**
* see {@link WhitelistableTransaction} for more information on a whitelistable transaction
*/
public WhitelistableTransaction whitelistableTransaction() {
- return new WhitelistableTransaction(baseTransaction.toEnvelopeXdrBase64(),
+ return new WhitelistableTransaction(baseTransaction().toEnvelopeXdrBase64(),
Network.current().getNetworkPassphrase());
}
@@ -71,26 +44,18 @@ public WhitelistableTransaction whitelistableTransaction() {
* Transaction need to have at least one signature.
*/
public String transactionEnvelope() {
- return baseTransaction.toEnvelopeXdrBase64();
- }
-
- public long sequenceNumber() {
- return baseTransaction.getSequenceNumber();
+ return baseTransaction().toEnvelopeXdrBase64();
}
public Operation[] operations() {
- return baseTransaction.getOperations();
- }
-
- public ListSee {@link KinAccount#sendTransactionSync(RawTransaction)} for possibles errors
+ *See {@link KinAccount#sendTransactionSync(TransactionBase)} for possibles errors
* @param transaction is the transaction object to send. * @return {@code RequestTransaction instance from previously build TransactionEnvelope
- *
- * @param transactionEnvelope a Base-64 encoded TransactionEnvelope
- */
- public static RawTransaction decodeTransaction(String transactionEnvelope) throws DecodeTransactionException {
- try {
- kin.base.Transaction transaction = kin.base.Transaction.fromEnvelopeXdr(transactionEnvelope);
- return new RawTransaction(transaction);
- } catch (IOException e) {
- throw new DecodeTransactionException(e.getMessage(), e.getCause());
- }
- }
-
public Memo memo() {
return baseTransaction().getMemo();
}
- /**
- * see {@link WhitelistableTransaction} for more information on a whitelistable transaction
- */
- public WhitelistableTransaction whitelistableTransaction() {
- return new WhitelistableTransaction(baseTransaction().toEnvelopeXdrBase64(),
- Network.current().getNetworkPassphrase());
- }
-
- /**
- * Returns base64-encoded TransactionEnvelope object.
- * Transaction need to have at least one signature.
- */
- public String transactionEnvelope() {
- return baseTransaction().toEnvelopeXdrBase64();
- }
-
public Operation[] operations() {
return baseTransaction().getOperations();
}
- /**
- * @return TimeBounds, or null (representing no time restrictions)
- */
- public TimeBounds timeBounds() {
- return baseTransaction().getTimeBounds();
- }
-
- /**
- * Adds a new signature to this transaction.
- * @param account {@link KinAccount} object which is the account who we add his signature.
- */
- public void addSignature(KinAccount account) {
- baseTransaction().sign(((KinAccountImpl) account).getKeyPair());
- }
-
}
diff --git a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/TransactionBase.java b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/TransactionBase.java
index 6ccba6ee..14c9935a 100644
--- a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/TransactionBase.java
+++ b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/TransactionBase.java
@@ -1,10 +1,18 @@
package kin.sdk;
+import java.io.IOException;
+import java.math.BigDecimal;
import java.util.List;
+import kin.base.MemoText;
+import kin.base.Network;
+import kin.base.Operation;
+import kin.base.PaymentOperation;
+import kin.base.TimeBounds;
import kin.base.Transaction;
import kin.base.xdr.DecoratedSignature;
+import kin.sdk.exception.DecodeTransactionException;
-public class TransactionBase {
+public abstract class TransactionBase {
private final Transaction baseTransaction;
@@ -12,6 +20,42 @@ public TransactionBase(kin.base.Transaction baseTransaction) {
this.baseTransaction = baseTransaction;
}
+ /**
+ * Creates a RawTransaction or a PaymentTransaction instance from previously build TransactionEnvelope
+ *
+ * @param transactionEnvelope a Base-64 encoded TransactionEnvelope
+ */
+ public static TransactionBase decodeTransaction(String transactionEnvelope) throws DecodeTransactionException {
+ try {
+ kin.base.Transaction transaction = kin.base.Transaction.fromEnvelopeXdr(transactionEnvelope);
+ Operation[] operations = transaction.getOperations();
+ for (Operation operation : operations) {
+ if (operation instanceof PaymentOperation) {
+ PaymentOperation paymentOperation = (PaymentOperation) operation;
+ return new PaymentTransaction(transaction, paymentOperation.getDestination().getAccountId(),
+ new BigDecimal(paymentOperation.getAmount()), ((MemoText) transaction.getMemo()).getText());
+ }
+ }
+ return new RawTransaction(transaction);
+ } catch (IOException e) {
+ throw new DecodeTransactionException(e.getMessage(), e.getCause());
+ }
+ }
+
+ /**
+ * Creates a RawTransaction instance from previously build TransactionEnvelope
+ *
+ * @param transactionEnvelope a Base-64 encoded TransactionEnvelope
+ */
+ public static RawTransaction decodeRawTransaction(String transactionEnvelope) throws DecodeTransactionException {
+ try {
+ kin.base.Transaction transaction = kin.base.Transaction.fromEnvelopeXdr(transactionEnvelope);
+ return new RawTransaction(transaction);
+ } catch (IOException e) {
+ throw new DecodeTransactionException(e.getMessage(), e.getCause());
+ }
+ }
+
kin.base.Transaction baseTransaction() {
return baseTransaction;
}
@@ -38,8 +82,41 @@ public String source() {
return baseTransaction.getSourceAccount().getAccountId();
}
+ /**
+ * @return TimeBounds, or null (representing no time restrictions)
+ */
+ public TimeBounds timeBounds() {
+ return baseTransaction.getTimeBounds();
+ }
+
public ListSee {@link KinAccount#buildTransactionSync(String, BigDecimal, int)} for possibles errors
+ *See {@link KinAccount#buildPaymentTransactionSync(String, BigDecimal, int)} for possibles errors
* @param publicAddress the account address to send the specified kin amount. * @param amount the amount of kin to transfer. * @param fee the amount of fee(in stroops) for this transfer. * @return {@code RequestSee {@link KinAccount#buildTransactionSync(String, BigDecimal, int, String)} for possibles errors
+ *See {@link KinAccount#buildPaymentTransactionSync(String, BigDecimal, int, String)} for possibles errors
* @param publicAddress the account address to send the specified kin amount. * @param amount the amount of kin to transfer. * @param fee the amount of fee(in stroops) for this transfer. * @param memo An optional string, can contain a utf-8 string up to 21 bytes in length, included on the transaction record. * @return {@code RequestRawTransaction or a PaymentTransaction instance from previously build TransactionEnvelope
+ * Creates a RawTransaction or a PaymentTransaction instance from previously build
+ * TransactionEnvelope
*
* @param transactionEnvelope a Base-64 encoded TransactionEnvelope
*/
@@ -33,7 +34,7 @@ public static TransactionBase decodeTransaction(String transactionEnvelope) thro
PaymentOperation paymentOperation = null;
for (Operation operation : operations) {
if (operation instanceof PaymentOperation) {
- paymentOperationCount ++;
+ paymentOperationCount++;
paymentOperation = (PaymentOperation) operation;
}
}
@@ -109,8 +110,7 @@ public ListGET /accounts/{account}/controlled_balances
+ * Requests GET /accounts/{account}/controlled_accounts
*
* @param account the account in which we get all his controlled accounts
*/
public ControlledAccountsResponse controlledAccounts(KeyPair account) throws IOException {
- this.setSegments("accounts", account.getAccountId(), "controlled_balances");
+ this.setSegments("accounts", account.getAccountId(), "controlled_accounts");
return this.controlledAccounts(this.buildUri());
}
diff --git a/kin-sdk/kin-sdk-lib/src/androidTest/java/kin/sdk/WhitelistServiceForTest.java b/kin-sdk/kin-sdk-lib/src/androidTest/java/kin/sdk/WhitelistServiceForTest.java
index 3e727e5a..0be9de42 100644
--- a/kin-sdk/kin-sdk-lib/src/androidTest/java/kin/sdk/WhitelistServiceForTest.java
+++ b/kin-sdk/kin-sdk-lib/src/androidTest/java/kin/sdk/WhitelistServiceForTest.java
@@ -1,15 +1,12 @@
package kin.sdk;
-import java.io.IOException;
-import java.util.concurrent.TimeUnit;
-import okhttp3.MediaType;
-import okhttp3.OkHttpClient;
-import okhttp3.Request;
-import okhttp3.RequestBody;
-import okhttp3.Response;
+import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+
public class WhitelistServiceForTest {
@@ -41,8 +38,8 @@ String whitelistTransaction(WhitelistableTransaction whitelistableTransaction) t
private String toJson(WhitelistableTransaction whitelistableTransaction) throws JSONException {
JSONObject jo = new JSONObject();
- jo.put("envelop", whitelistableTransaction.getTransactionPayload());
- jo.put("network_id", whitelistableTransaction.getNetworkPassphrase());
+ jo.put("envelop", whitelistableTransaction.transactionPayload());
+ jo.put("network_id", whitelistableTransaction.networkPassphrase());
return jo.toString();
}
From 27f450479198e79b34acc38f8614be96dd38d280 Mon Sep 17 00:00:00 2001
From: Amitai Efrati <42765949+drEfrati@users.noreply.github.com>
Date: Sun, 16 Jun 2019 16:34:29 +0300
Subject: [PATCH 47/56] Update README.md
---
kin-backup-and-restore/README.md | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/kin-backup-and-restore/README.md b/kin-backup-and-restore/README.md
index 297766fb..60ebee9c 100644
--- a/kin-backup-and-restore/README.md
+++ b/kin-backup-and-restore/README.md
@@ -73,7 +73,9 @@ Both callbacks have the same 3 methods:
- `onSuccess` is called when the operation is completed successfully. In the Restore callback, it has a `KinClient`(the updated one) and `KinAccount` object, which is the restored account.
- `onCancel` is called when the user leaves the backup or restore activity and returns to the previous activity.
- `onFailure()` is called if there is an error in the backup or restore process.
+
###### Creating Backup Callbacks
+
```java
backupAndRestoreManager.registerBackupCallback(new BackupCallback() {
@Override
@@ -91,9 +93,8 @@ backupAndRestoreManager.registerBackupCallback(new BackupCallback() {
// Here you can handle the failure.
}
});
-}
-});
```
+
###### Creating Restore Callbacks
```java
backupAndRestoreManager.registerRestoreCallback(new RestoreCallback() {
From 83570ae0c06bedf335d3b7b8a4dcd9e04b7eff27 Mon Sep 17 00:00:00 2001
From: Amitai Efrati <42765949+drEfrati@users.noreply.github.com>
Date: Sun, 16 Jun 2019 16:39:44 +0300
Subject: [PATCH 48/56] Update README.md
---
kin-backup-and-restore/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/kin-backup-and-restore/README.md b/kin-backup-and-restore/README.md
index ca34c74f..5316701c 100644
--- a/kin-backup-and-restore/README.md
+++ b/kin-backup-and-restore/README.md
@@ -78,6 +78,7 @@ Both callbacks have the same 3 methods:
```java
backupAndRestoreManager.registerBackupCallback(new BackupCallback() {
+
@Override
public void onSuccess() {
// Here you can handle the success.
@@ -98,6 +99,7 @@ backupAndRestoreManager.registerBackupCallback(new BackupCallback() {
###### Creating Restore Callbacks
```java
backupAndRestoreManager.registerRestoreCallback(new RestoreCallback() {
+
@Override
public void onSuccess(KinClient kinClient, KinAccount kinAccount) {
// Here you can handle the success.
From b2e13c6ea553ff6ddacfaa76be41c50510085108 Mon Sep 17 00:00:00 2001
From: Amitai Efrati GET /accounts/{account}/controlled_accounts
*
diff --git a/kin-sdk/kin-sdk-lib/src/androidTest/java/kin/sdk/IntegConsts.java b/kin-sdk/kin-sdk-lib/src/androidTest/java/kin/sdk/IntegConsts.java
index 6b3f329a..5ddcb7c3 100644
--- a/kin-sdk/kin-sdk-lib/src/androidTest/java/kin/sdk/IntegConsts.java
+++ b/kin-sdk/kin-sdk-lib/src/androidTest/java/kin/sdk/IntegConsts.java
@@ -3,7 +3,7 @@
final class IntegConsts {
- static final String TEST_NETWORK_URL = "http://horizon-testnet-one-wallet.kininfrastructure.com/";
+ static final String TEST_NETWORK_URL = "https://horizon-testnet.kininfrastructure.com/";
static final String TEST_NETWORK_ID = "Kin Testnet ; December 2018";
static final String URL_CREATE_ACCOUNT = "https://friendbot.developers.kinecosystem.com?addr=%s&amount=%s";
static final String URL_FUND = "https://friendbot.developers.kinecosystem.com/fund?addr=%s&amount="; // faucet
diff --git a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/Environment.java b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/Environment.java
index 06ffd937..ca54a42e 100644
--- a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/Environment.java
+++ b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/Environment.java
@@ -1,9 +1,9 @@
package kin.sdk;
-import static kin.sdk.Utils.checkNotEmpty;
-
import kin.base.Network;
+import static kin.sdk.Utils.checkNotEmpty;
+
/**
* Provides blockchain network details
*/
@@ -13,9 +13,8 @@ public class Environment {
new Environment("https://horizon.kinfederation.com",
"Kin Mainnet ; December 2018");
- // TODO: 2019-06-02 change this and other test places to the regular test-net
public static final Environment TEST =
- new Environment("http://horizon-testnet-one-wallet.kininfrastructure.com//",
+ new Environment("https://horizon-testnet.kininfrastructure.com/",
"Kin Testnet ; December 2018");
private final String networkUrl;
From e8e28eb58ae722c8bfd7ab4b09ce48a0e1a5c982 Mon Sep 17 00:00:00 2001
From: Amitai Efrati Memos can be one of the following types:
+ *RawTransaction or a PaymentTransaction instance from previously build
- * TransactionEnvelope
+ * TransactionEnvelope string representation.
+ *
+ * Once a transaction is ready to be signed, the transaction object is wrapped in an object called + * a Transaction Envelope, which contains the transaction as well as a set of signatures. + * A Transaction Envelope can be represented as a string base-64 encoded.
* * @param transactionEnvelope a Base-64 encodedTransactionEnvelope
+ * @return a TransactionBase instance from a previously build transaction envelope.
*/
public static TransactionBase decodeTransaction(String transactionEnvelope) throws DecodeTransactionException {
try {
@@ -51,6 +52,7 @@ public static TransactionBase decodeTransaction(String transactionEnvelope) thro
/**
* Creates a RawTransaction instance from previously build TransactionEnvelope
+ * See {@link TransactionBase#decodeTransaction(String)} for more details
* * @param transactionEnvelope a Base-64 encodedTransactionEnvelope
*/
@@ -68,7 +70,11 @@ kin.base.Transaction baseTransaction() {
}
/**
- * Returns fee paid for transaction in kin base unit which is quark (1 quark = 0.00001 KIN).
+ * Each transaction sets a fee that is paid by the source account.
+ * If this fee is below the network minimum the transaction will fail.
+ * The more operations in the transaction, the greater the required fee.
+ *
+ * @return the fee paid for transaction in kin base unit which is quark (1 quark = 0.00001 KIN).
*/
public int fee() {
return baseTransaction.getFee();
@@ -82,6 +88,19 @@ public TransactionId id() {
}
/**
+ *
+ * Each transaction has a sequence number. Transactions follow a strict ordering rule when it comes to processing
+ * of transactions per account. For the transaction to be valid, the sequence number must be 1 greater than the
+ * sequence number stored in the source account entry when the transaction is applied. As the transaction is
+ * applied, the source account’s stored sequence number is incremented by 1 before applying operations. If the
+ * sequence number on the account is 4, then the incoming transaction should have a sequence number of 5. After
+ * the transaction is applied, the sequence number on the account is bumped to 5.
+ * Adds a new signature to this transaction.
+ *Transactions always need authorization from at least one public key in order to be considered valid. + * Generally, transactions only need authorization from the public key of the source account.
+ *Up to 20 signatures can be attached to a transaction. See next section for more information. A transaction is + * considered invalid if it includes signatures that aren’t needed to authorize the transaction—superfluous + * signatures aren’t allowed. + * Signatures are required to authorize operations and to authorize changes to the source account (fee and + * sequence number).
+ *In two cases, a transaction may need more than one signature. If the transaction has operations that + * affect more than one account, it will need authorization from every account in question. + * A transaction will also need additional signatures if the account associated with the transaction has multiple public keys.
+ *Currently we use the ed25519 signature scheme
* * @param account {@link KinAccount} object which is the account who we add his signature. */ diff --git a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/TransactionBuilder.java b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/TransactionBuilder.java index b46138fc..bde51068 100644 --- a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/TransactionBuilder.java +++ b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/TransactionBuilder.java @@ -1,27 +1,25 @@ package kin.sdk; import android.text.TextUtils; -import kin.base.KeyPair; -import kin.base.Memo; -import kin.base.Operation; -import kin.base.TimeBounds; -import kin.base.Transaction; +import kin.base.*; import kin.base.Transaction.Builder; -import kin.base.TransactionBuilderAccount; public class TransactionBuilder { private final Builder builder; private final KeyPair account; private final String appId; - private String memo; + private Memo memo; /** * Construct a new transaction builder. * * @param account The source account for this transaction. This account is the account - * @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. + * @param sourceAccount This is the account that originates the transaction. The transaction must be signed by this account, + * and the transaction fee must be paid by this account. The sequence number of this transaction is based off this account. + * This account is the account who will use a sequence number. When build() is called, the account object's sequence number + * will be incremented. + * * @param appId is a 3-4 character string which is added to each transaction memo to identify your application. * * appId must contain only digits and upper and/or lower case letters. String length must be 3 or 4. */ @@ -36,7 +34,13 @@ public int getOperationsCount() { } /** - * Adds a new operation to this transaction. + *Adds a new operation to this transaction.
+ * + * Transactions contain an arbitrary list of operations inside them. Typically there is just one operation, + * but it’s possible to have multiple (up to 100). + * Operations are executed in order as one ACID transaction, meaning that either all operations are applied or none are. + * If any operation fails, the whole transaction fails. If operations are on accounts other than the source account, + * then they require signatures of the accounts in question. * * @return Builder object so you can chain methods. * @see Operation @@ -60,18 +64,32 @@ public TransactionBuilder setFee(int fee) { /** * Adds a memo to this transaction. - * @param memo It's an optional parameter and should contain extra information - * + * @param memo is an optional object that contains optional extra information. It is the responsibility + * of the client to interpret this value. + *Memos can be one of the following types:
+ *Adds a time-bounds to this transaction.
+ * + * Time-bounds is an optional. + *See {@link ControlledAccount} for more information on a controlled account
@@ -169,7 +166,21 @@ public interface KinAccount { RequestSee {@link ControlledAccount} for more information on a controlled account
+ *See {@link KinAccount#getAggregatedBalanceSync()} for possibles errors
+ * + * @return {@code RequestNote: This method accesses the network, and should not be called on the android main thread.
* * @return the aggregated balance in kin @@ -179,6 +190,17 @@ public interface KinAccount { @NonNull Balance getAggregatedBalanceSync() throws OperationFailedException; + /** + * Get the current confirmed aggregated balance in kin of a given account + *Note: This method accesses the network, and should not be called on the android main thread.
+ * + * @return the aggregated balance in kin + * @throws AccountNotFoundException if account was not created + * @throws OperationFailedException any other error + */ + @NonNull + Balance getAggregatedBalanceSync(String publicAddress) throws OperationFailedException; + /** * Create {@link Request} for getting list of controlled accounts * It is a list of all accounts controlled by the master account. diff --git a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/KinAccountImpl.java b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/KinAccountImpl.java index bb88b514..3cf49fa0 100644 --- a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/KinAccountImpl.java +++ b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/KinAccountImpl.java @@ -2,13 +2,14 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; -import java.math.BigDecimal; -import java.util.List; import kin.base.KeyPair; import kin.sdk.exception.AccountDeletedException; import kin.sdk.exception.CryptoException; import kin.sdk.exception.OperationFailedException; +import java.math.BigDecimal; +import java.util.List; + final class KinAccountImpl extends AbstractKinAccount { @@ -84,6 +85,15 @@ public Balance getAggregatedBalanceSync() throws OperationFailedException { return accountInfoRetriever.getAggregatedBalance(account.getAccountId()); } + @NonNull + @Override + public Balance getAggregatedBalanceSync(String publicAddress) throws OperationFailedException { + if (publicAddress == null || publicAddress.length() == 0) { + throw new IllegalArgumentException("public address not valid"); + } + return accountInfoRetriever.getAggregatedBalance(publicAddress); + } + @NonNull @Override public ListSee {@link ControlledAccount} for more information on a controlled account
- *See {@link KinAccount#getAggregatedBalanceSync()} for possibles errors
- * - * @return {@code RequestSee {@link ControlledAccount} for more information on a controlled account
- *See {@link KinAccount#getAggregatedBalanceSync()} for possibles errors
- * - * @return {@code RequestNote: This method accesses the network, and should not be called on the android main thread.
- * - * @return the aggregated balance in kin - * @throws AccountNotFoundException if account was not created - * @throws OperationFailedException any other error - */ - @NonNull - Balance getAggregatedBalanceSync() throws OperationFailedException; - - /** - * Get the current confirmed aggregated balance in kin of a given account - *Note: This method accesses the network, and should not be called on the android main thread.
- * - * @return the aggregated balance in kin - * @throws AccountNotFoundException if account was not created - * @throws OperationFailedException any other error - */ - @NonNull - Balance getAggregatedBalanceSync(String publicAddress) throws OperationFailedException; - - /** - * Create {@link Request} for getting list of controlled accounts - * It is a list of all accounts controlled by the master account. - *See {@link ControlledAccount} for more information on a controlled account
- *See {@link KinAccount#getControlledAccountsSync()} for possibles errors
- * - * @return {@code RequestNote: This method accesses the network, and should not be called on the android main thread.
- * - * @return the list of controlled accounts. Could be empty if no controlled accounts. - * @throws AccountNotFoundException if account was not created - * @throws OperationFailedException any other error - */ - @NonNull - ListSee {@link KinAccount#getAccountDataSync()} for possibles errors
diff --git a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/KinAccountImpl.java b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/KinAccountImpl.java index 3cf49fa0..8d2c20c0 100644 --- a/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/KinAccountImpl.java +++ b/kin-sdk/kin-sdk-lib/src/main/java/kin/sdk/KinAccountImpl.java @@ -8,7 +8,6 @@ import kin.sdk.exception.OperationFailedException; import java.math.BigDecimal; -import java.util.List; final class KinAccountImpl extends AbstractKinAccount { @@ -78,29 +77,6 @@ public Balance getBalanceSync() throws OperationFailedException { return accountInfoRetriever.getBalance(account.getAccountId()); } - @NonNull - @Override - public Balance getAggregatedBalanceSync() throws OperationFailedException { - checkValidAccount(); - return accountInfoRetriever.getAggregatedBalance(account.getAccountId()); - } - - @NonNull - @Override - public Balance getAggregatedBalanceSync(String publicAddress) throws OperationFailedException { - if (publicAddress == null || publicAddress.length() == 0) { - throw new IllegalArgumentException("public address not valid"); - } - return accountInfoRetriever.getAggregatedBalance(publicAddress); - } - - @NonNull - @Override - public ListpN
z@x-2Y_1f0CCtQm=H|Ro5W}I&b9fgSXwB$vok}$!}497TD
zNE&4E%3s^XUUsKT0HsAT(Dz{1>&_RngF^U2lTMZ?Tyaw%PBPdWy4R 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: Use static methods to generate any of above types. Returns hex representation of bytes contained in this memo. Example: Returns hex representation of bytes contained in this memo. Example: Returns hex representation of bytes contained in this memo until null byte (0x00) is found. Example: Returns hex representation of bytes contained in this memo until null byte (0x00) is found. Example: Increase timeout to prevent timeout exception for transaction with ledger close
* time above default of 10 sec TimeBounds represents the time interval that a transaction is valid.eewR_?-urgv
z7t$|*Bamba4<)&QMu{1XWRv_WhXSaK!$nqSyPXj$_R`P7b$2GQqEQ)tB2gbwh`+jL
z3aP$cB!VBC
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()),
- ;
+ /**
+ * 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;
- }
+ private final int value;
- public int getValue() {
- return value;
- }
+ AccountFlag(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/AccountMergeOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/AccountMergeOperation.java
index 25f31919..db6b0108 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/AccountMergeOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/AccountMergeOperation.java
@@ -1,13 +1,14 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.AccountID;
import kin.base.xdr.Operation.OperationBody;
import kin.base.xdr.OperationType;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents AccountMerge operation.
+ *
* @see List of Operations
*/
public class AccountMergeOperation extends Operation {
@@ -37,6 +38,7 @@ OperationBody toOperationBody() {
/**
* Builds AccountMerge operation.
+ *
* @see AccountMergeOperation
*/
public static class Builder {
@@ -50,6 +52,7 @@ public static class Builder {
/**
* Creates a new AccountMerge builder.
+ *
* @param destination The account that receives the remaining XLM balance of the source account.
*/
public Builder(KeyPair destination) {
@@ -58,6 +61,7 @@ public Builder(KeyPair destination) {
/**
* Set source account of this operation
+ *
* @param sourceAccount Source account
* @return Builder object so you can chain methods.
*/
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/AllowTrustOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/AllowTrustOperation.java
index 45a76921..58620c42 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/AllowTrustOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/AllowTrustOperation.java
@@ -1,133 +1,137 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.AccountID;
import kin.base.xdr.AllowTrustOp;
import kin.base.xdr.AssetType;
import kin.base.xdr.OperationType;
+import static kin.base.Util.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
- kin.base.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);
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.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();
+ 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;
}
/**
- * 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.
+ * The account of the recipient of the trustline.
*/
- public Builder(KeyPair trustor, String assetCode, boolean authorize) {
- this.trustor = trustor;
- this.assetCode = assetCode;
- this.authorize = authorize;
+ public KeyPair getTrustor() {
+ return trustor;
}
/**
- * Set source account of this operation
- * @param sourceAccount Source account
- * @return Builder object so you can chain methods.
+ * 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 Builder setSourceAccount(KeyPair sourceAccount) {
- mSourceAccount = sourceAccount;
- return this;
+ public String getAssetCode() {
+ return assetCode;
+ }
+
+ /**
+ * Flag indicating whether the trustline is authorized.
+ */
+ public boolean getAuthorize() {
+ return authorize;
+ }
+
+ @Override
+ kin.base.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);
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.ALLOW_TRUST);
+ body.setAllowTrustOp(op);
+ return body;
}
/**
- * Builds an operation
+ * Builds AllowTrust operation.
+ *
+ * @see AllowTrustOperation
*/
- public AllowTrustOperation build() {
- AllowTrustOperation operation = new AllowTrustOperation(trustor, assetCode, authorize);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ 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/kin-sdk/kin-base/src/main/java/kin/base/Asset.java b/kin-sdk/kin-base/src/main/java/kin/base/Asset.java
index be40dc16..5ae019e4 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Asset.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Asset.java
@@ -2,63 +2,67 @@
/**
* Base Asset class.
+ *
* @see Assets
*/
public abstract class Asset {
- Asset() {}
+ Asset() {
+ }
- /**
- * 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();
+ /**
+ * 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(kin.base.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());
+ /**
+ * Generates Asset object from a given XDR object
+ *
+ * @param xdr XDR object
+ */
+ public static Asset fromXdr(kin.base.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:
- *
- *
- */
- public abstract String getType();
+ /**
+ * Returns asset type. Possible types:
+ * nativecredit_alphanum4credit_alphanum12
+ *
+ */
+ public abstract String getType();
- @Override
- public abstract boolean equals(Object object);
+ @Override
+ public abstract boolean equals(Object object);
- /**
- * Generates XDR object from a given Asset object
- */
- public abstract kin.base.xdr.Asset toXdr();
+ /**
+ * Generates XDR object from a given Asset object
+ */
+ public abstract kin.base.xdr.Asset toXdr();
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/AssetCodeLengthInvalidException.java b/kin-sdk/kin-base/src/main/java/kin/base/AssetCodeLengthInvalidException.java
index 499d23b4..d1d48acf 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/AssetCodeLengthInvalidException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/AssetCodeLengthInvalidException.java
@@ -2,6 +2,7 @@
/**
* Indicates that asset code is not valid for a specified asset class
+ *
* @see AssetTypeCreditAlphaNum4
* @see AssetTypeCreditAlphaNum12
*/
@@ -13,4 +14,4 @@ public AssetCodeLengthInvalidException() {
public AssetCodeLengthInvalidException(String message) {
super(message);
}
-}
\ No newline at end of file
+}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum.java b/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum.java
index d678fcf1..032ea0af 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum.java
@@ -1,11 +1,12 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import java.util.Arrays;
+import static kin.base.Util.checkNotNull;
+
/**
* Base class for AssetTypeCreditAlphaNum4 and AssetTypeCreditAlphaNum12 subclasses.
+ *
* @see Assets
*/
public abstract class AssetTypeCreditAlphaNum extends Asset {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum12.java b/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum12.java
index 653ff307..320f2ee3 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum12.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum12.java
@@ -5,37 +5,39 @@
/**
* 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();
+ /**
+ * 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 String getType() {
+ return "credit_alphanum12";
+ }
- @Override
- public kin.base.xdr.Asset toXdr() {
- kin.base.xdr.Asset xdr = new kin.base.xdr.Asset();
- xdr.setDiscriminant(AssetType.ASSET_TYPE_CREDIT_ALPHANUM12);
- kin.base.xdr.Asset.AssetAlphaNum12 credit = new kin.base.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;
- }
+ @Override
+ public kin.base.xdr.Asset toXdr() {
+ kin.base.xdr.Asset xdr = new kin.base.xdr.Asset();
+ xdr.setDiscriminant(AssetType.ASSET_TYPE_CREDIT_ALPHANUM12);
+ kin.base.xdr.Asset.AssetAlphaNum12 credit = new kin.base.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/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum4.java b/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum4.java
index dc87edc7..edcc4278 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum4.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeCreditAlphaNum4.java
@@ -5,37 +5,39 @@
/**
* 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();
+ /**
+ * 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 String getType() {
+ return "credit_alphanum4";
+ }
- @Override
- public kin.base.xdr.Asset toXdr() {
- kin.base.xdr.Asset xdr = new kin.base.xdr.Asset();
- xdr.setDiscriminant(AssetType.ASSET_TYPE_CREDIT_ALPHANUM4);
- kin.base.xdr.Asset.AssetAlphaNum4 credit = new kin.base.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;
- }
+ @Override
+ public kin.base.xdr.Asset toXdr() {
+ kin.base.xdr.Asset xdr = new kin.base.xdr.Asset();
+ xdr.setDiscriminant(AssetType.ASSET_TYPE_CREDIT_ALPHANUM4);
+ kin.base.xdr.Asset.AssetAlphaNum4 credit = new kin.base.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/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeNative.java b/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeNative.java
index e36132bf..d47eae16 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeNative.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/AssetTypeNative.java
@@ -4,31 +4,33 @@
/**
* Represents Stellar native asset - lumens (XLM)
+ *
* @see Assets
*/
public final class AssetTypeNative extends Asset {
- public AssetTypeNative() {}
+ public AssetTypeNative() {
+ }
- @Override
- public String getType() {
- return "native";
- }
+ @Override
+ public String getType() {
+ return "native";
+ }
- @Override
- public boolean equals(Object object) {
- return this.getClass().equals(object.getClass());
- }
+ @Override
+ public boolean equals(Object object) {
+ return this.getClass().equals(object.getClass());
+ }
- @Override
- public int hashCode() {
- return 0;
- }
+ @Override
+ public int hashCode() {
+ return 0;
+ }
- @Override
- public kin.base.xdr.Asset toXdr() {
- kin.base.xdr.Asset xdr = new kin.base.xdr.Asset();
- xdr.setDiscriminant(AssetType.ASSET_TYPE_NATIVE);
- return xdr;
- }
+ @Override
+ public kin.base.xdr.Asset toXdr() {
+ kin.base.xdr.Asset xdr = new kin.base.xdr.Asset();
+ xdr.setDiscriminant(AssetType.ASSET_TYPE_NATIVE);
+ return xdr;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/ChangeTrustOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/ChangeTrustOperation.java
index abc76635..3d4d4451 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/ChangeTrustOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/ChangeTrustOperation.java
@@ -1,98 +1,102 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.ChangeTrustOp;
import kin.base.xdr.Int64;
import kin.base.xdr.OperationType;
+import static kin.base.Util.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
- kin.base.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);
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.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());
+ private ChangeTrustOperation(Asset asset, String limit) {
+ this.asset = checkNotNull(asset, "asset cannot be null");
+ this.limit = checkNotNull(limit, "limit cannot be null");
}
/**
- * 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.
+ * 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 Builder(Asset asset, String limit) {
- this.asset = checkNotNull(asset, "asset cannot be null");
- this.limit = checkNotNull(limit, "limit cannot be null");
+ public Asset getAsset() {
+ return asset;
}
/**
- * Set source account of this operation
- * @param sourceAccount Source account
- * @return Builder object so you can chain methods.
+ * 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 Builder setSourceAccount(KeyPair sourceAccount) {
- mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null");
- return this;
+ public String getLimit() {
+ return limit;
+ }
+
+ @Override
+ kin.base.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);
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.CHANGE_TRUST);
+ body.setChangeTrustOp(op);
+ return body;
}
/**
- * Builds an operation
+ * Builds ChangeTrust operation.
+ *
+ * @see ChangeTrustOperation
*/
- public ChangeTrustOperation build() {
- ChangeTrustOperation operation = new ChangeTrustOperation(asset, limit);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ 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/kin-sdk/kin-base/src/main/java/kin/base/CreateAccountOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/CreateAccountOperation.java
index e846b637..3247836a 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/CreateAccountOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/CreateAccountOperation.java
@@ -1,105 +1,110 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.AccountID;
import kin.base.xdr.CreateAccountOp;
import kin.base.xdr.Int64;
import kin.base.xdr.OperationType;
+import static kin.base.Util.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
- kin.base.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);
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.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;
+ private CreateAccountOperation(KeyPair destination, String startingBalance) {
+ this.destination = checkNotNull(destination, "destination cannot be null");
+ this.startingBalance = checkNotNull(startingBalance, "startingBalance cannot be null");
+ }
/**
- * Construct a new CreateAccount builder from a CreateAccountOp XDR.
- * @param op {@link CreateAccountOp}
+ * Amount of XLM to send to the newly created account.
*/
- Builder(CreateAccountOp op) {
- destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID());
- startingBalance = Operation.fromXdrAmount(op.getStartingBalance().getInt64().longValue());
+ public String getStartingBalance() {
+ return startingBalance;
}
/**
- * 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.
+ * Account that is created and funded
*/
- public Builder(KeyPair destination, String startingBalance) {
- this.destination = destination;
- this.startingBalance = startingBalance;
+ public KeyPair getDestination() {
+ return destination;
}
- /**
- * 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;
+ @Override
+ kin.base.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);
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.CREATE_ACCOUNT);
+ body.setCreateAccountOp(op);
+ return body;
}
/**
- * Builds an operation
+ * Builds CreateAccount operation.
+ *
+ * @see CreateAccountOperation
*/
- public CreateAccountOperation build() {
- CreateAccountOperation operation = new CreateAccountOperation(destination, startingBalance);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ 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/kin-sdk/kin-base/src/main/java/kin/base/CreatePassiveOfferOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/CreatePassiveOfferOperation.java
index 9227bd3c..a3d9e005 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/CreatePassiveOfferOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/CreatePassiveOfferOperation.java
@@ -1,135 +1,141 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import java.math.BigDecimal;
+
import kin.base.xdr.CreatePassiveOfferOp;
import kin.base.xdr.Int64;
import kin.base.xdr.OperationType;
+import static kin.base.Util.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
- kin.base.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());
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.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;
+ 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");
+ }
/**
- * Construct a new CreatePassiveOffer builder from a CreatePassiveOfferOp XDR.
- * @param op
+ * The asset being sold in this operation
*/
- 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();
+ public Asset getSelling() {
+ return selling;
}
/**
- * 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.
+ * The asset being bought in this operation
*/
- 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");
+ public Asset getBuying() {
+ return buying;
}
/**
- * Sets the source account for this operation.
- * @param sourceAccount The operation's source account.
- * @return Builder object so you can chain methods.
+ * Amount of selling being sold.
*/
- public Builder setSourceAccount(KeyPair sourceAccount) {
- mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null");
- return this;
+ public String getAmount() {
+ return amount;
+ }
+
+ /**
+ * Price of 1 unit of selling in terms of buying.
+ */
+ public String getPrice() {
+ return price;
+ }
+
+ @Override
+ kin.base.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());
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.CREATE_PASSIVE_OFFER);
+ body.setCreatePassiveOfferOp(op);
+
+ return body;
}
/**
- * Builds an operation
+ * Builds CreatePassiveOffer operation.
+ *
+ * @see CreatePassiveOfferOperation
*/
- public CreatePassiveOfferOperation build() {
- CreatePassiveOfferOperation operation = new CreatePassiveOfferOperation(selling, buying, amount, price);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ 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/kin-sdk/kin-base/src/main/java/kin/base/FormatException.java b/kin-sdk/kin-base/src/main/java/kin/base/FormatException.java
index a60f1d8a..b55f2563 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/FormatException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/FormatException.java
@@ -2,14 +2,15 @@
/**
* Indicates that there was a problem decoding strkey encoded string.
+ *
* @see KeyPair
*/
public class FormatException extends RuntimeException {
- public FormatException() {
- super();
- }
+ public FormatException() {
+ super();
+ }
- public FormatException(String message) {
- super(message);
- }
+ public FormatException(String message) {
+ super(message);
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/InflationOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/InflationOperation.java
index a6242aa6..e2695f79 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/InflationOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/InflationOperation.java
@@ -4,6 +4,7 @@
/**
* Represents Inflation operation.
+ *
* @see List of Operations
*/
public class InflationOperation extends Operation {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/KeyPair.java b/kin-sdk/kin-base/src/main/java/kin/base/KeyPair.java
index 46c70864..c690f88d 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/KeyPair.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/KeyPair.java
@@ -1,6 +1,13 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
+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 java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -9,6 +16,7 @@
import java.security.Signature;
import java.security.SignatureException;
import java.util.Arrays;
+
import kin.base.xdr.DecoratedSignature;
import kin.base.xdr.PublicKey;
import kin.base.xdr.PublicKeyType;
@@ -17,242 +25,247 @@
import kin.base.xdr.SignerKeyType;
import kin.base.xdr.Uint256;
import kin.base.xdr.XdrDataOutputStream;
-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 static kin.base.Util.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));
- }
-
- /**
- * 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());
- }
-
- /**
- * Returns the raw 32 byte secret seed.
- */
- public byte[] getRawSecretSeed() {
- return 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);
+ 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;
}
- }
-
- 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.");
+
+ /**
+ * 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.
+ *
+ * @param seed The strkey encoded Stellar secret seed.
+ * @return {@link KeyPair}
+ * @see Using Password-Based Encryption
+ */
+ public static KeyPair fromSecretSeed(String seed) {
+ char[] charSeed = seed.toCharArray();
+ byte[] decoded = StrKey.decodeStellarSecretSeed(charSeed);
+ KeyPair keypair = fromSecretSeed(decoded);
+ Arrays.fill(charSeed, ' ');
+ return keypair;
}
- 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);
+
+ /**
+ * 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));
}
- }
-
- /**
- * 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);
-
- kin.base.xdr.Signature signature = new kin.base.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);
+
+ /**
+ * 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);
}
- }
- @Override
- public boolean equals(Object obj) {
- return super.equals(obj);
- }
+ /**
+ * 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));
+ }
+
+ /**
+ * 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());
+ }
+
+ /**
+ * Returns the raw 32 byte secret seed.
+ */
+ public byte[] getRawSecretSeed() {
+ return 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);
+
+ kin.base.xdr.Signature signature = new kin.base.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/kin-sdk/kin-base/src/main/java/kin/base/LedgerEntryChange.java b/kin-sdk/kin-base/src/main/java/kin/base/LedgerEntryChange.java
index 9bb81077..1fadddff 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/LedgerEntryChange.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/LedgerEntryChange.java
@@ -5,31 +5,31 @@
public class LedgerEntryChange {
- LedgerEntryChange() {
- }
+ LedgerEntryChange() {
+ }
- private Long lastModifiedLedgerSequence;
+ private Long lastModifiedLedgerSequence;
- public Long getLastModifiedLedgerSequence() {
- return this.lastModifiedLedgerSequence;
- }
+ public Long getLastModifiedLedgerSequence() {
+ return this.lastModifiedLedgerSequence;
+ }
- public static LedgerEntryChange fromXdr(LedgerEntry xdr) {
- LedgerEntryChange entryChange = null;
- switch (xdr.getData().getDiscriminant()) {
- case ACCOUNT:
- entryChange = AccountLedgerEntryChange.fromXdr(xdr.getData().getAccount());
- entryChange.lastModifiedLedgerSequence = xdr.getLastModifiedLedgerSeq().getUint32().longValue();
- break;
- case TRUSTLINE:
- entryChange = TrustLineLedgerEntryChange.fromXdr(xdr.getData().getTrustLine());
- entryChange.lastModifiedLedgerSequence = xdr.getLastModifiedLedgerSeq().getUint32().longValue();
- break;
- case OFFER:
- break;
- case DATA:
- break;
+ public static LedgerEntryChange fromXdr(LedgerEntry xdr) {
+ LedgerEntryChange entryChange = null;
+ switch (xdr.getData().getDiscriminant()) {
+ case ACCOUNT:
+ entryChange = AccountLedgerEntryChange.fromXdr(xdr.getData().getAccount());
+ entryChange.lastModifiedLedgerSequence = xdr.getLastModifiedLedgerSeq().getUint32().longValue();
+ break;
+ case TRUSTLINE:
+ entryChange = TrustLineLedgerEntryChange.fromXdr(xdr.getData().getTrustLine());
+ entryChange.lastModifiedLedgerSequence = xdr.getLastModifiedLedgerSeq().getUint32().longValue();
+ break;
+ case OFFER:
+ break;
+ case DATA:
+ break;
+ }
+ return entryChange;
}
- return entryChange;
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/LedgerEntryChanges.java b/kin-sdk/kin-base/src/main/java/kin/base/LedgerEntryChanges.java
index 25f3f2b9..7bd695bc 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/LedgerEntryChanges.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/LedgerEntryChanges.java
@@ -6,46 +6,46 @@
public class LedgerEntryChanges {
- private LedgerEntryChange[] ledgerEntryUpdates;
- private LedgerEntryChange[] ledgerEntryStates;
-
- public LedgerEntryChange[] getLedgerEntryStates() {
- return ledgerEntryStates;
- }
-
- public LedgerEntryChange[] getLedgerEntryUpdates() {
- return this.ledgerEntryUpdates;
- }
-
- public static LedgerEntryChanges fromXdr(kin.base.xdr.LedgerEntryChanges xdr) {
- LedgerEntryChanges ledgerEntryChanges = new LedgerEntryChanges();
- Listnativecredit_alphanum4credit_alphanum12value param.
- * @param name The name of data entry
- * @param value The value of data entry. nullnull will delete data entry.
+ * Data value
*/
- public Builder(String name, byte[] value) {
- this.name = checkNotNull(name, "name cannot be null");
- this.value = value;
+ public byte[] getValue() {
+ return 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;
+ @Override
+ kin.base.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);
+ }
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.MANAGE_DATA);
+ body.setManageDataOp(op);
+
+ return body;
}
- /**
- * Builds an operation
- */
- public ManageDataOperation build() {
- ManageDataOperation operation = new ManageDataOperation(name, value);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ 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/kin-sdk/kin-base/src/main/java/kin/base/ManageOfferOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/ManageOfferOperation.java
index b22dad39..423c5bdc 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/ManageOfferOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/ManageOfferOperation.java
@@ -1,164 +1,171 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import java.math.BigDecimal;
+
import kin.base.xdr.CreateAccountOp;
import kin.base.xdr.Int64;
import kin.base.xdr.ManageOfferOp;
import kin.base.xdr.OperationType;
import kin.base.xdr.Uint64;
+import static kin.base.Util.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
- kin.base.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);
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.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 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 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;
+ }
- private KeyPair mSourceAccount;
+ /**
+ * The asset being sold in this operation
+ */
+ public Asset getSelling() {
+ return selling;
+ }
/**
- * Construct a new CreateAccount builder from a CreateAccountOp XDR.
- * @param op {@link CreateAccountOp}
+ * The asset being bought in this operation
*/
- 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();
+ public Asset getBuying() {
+ return buying;
}
/**
- * Creates a new ManageOffer builder. If you want to update existing offer use
- * {@link 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.
+ * Amount of selling being sold.
*/
- 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");
+ public String getAmount() {
+ return amount;
}
/**
- * Sets offer ID. 0 creates a new offer. Set to existing offer ID to change it.
- * @param offerId
+ * Price of 1 unit of selling in terms of buying.
*/
- public Builder setOfferId(long offerId) {
- this.offerId = offerId;
- return this;
+ public String getPrice() {
+ return price;
}
/**
- * Sets the source account for this operation.
- * @param sourceAccount The operation's source account.
- * @return Builder object so you can chain methods.
+ * The ID of the offer.
*/
- public Builder setSourceAccount(KeyPair sourceAccount) {
- mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null");
- return this;
+ public long getOfferId() {
+ return offerId;
+ }
+
+ @Override
+ kin.base.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);
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.MANAGE_OFFER);
+ body.setManageOfferOp(op);
+
+ return body;
}
/**
- * Builds an operation
+ * Builds ManageOffer operation. If you want to update existing offer use
+ * {@link ManageOfferOperation.Builder#setOfferId(long)}.
+ *
+ * @see ManageOfferOperation
*/
- public ManageOfferOperation build() {
- ManageOfferOperation operation = new ManageOfferOperation(selling, buying, amount, price, offerId);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ 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 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/kin-sdk/kin-base/src/main/java/kin/base/Memo.java b/kin-sdk/kin-base/src/main/java/kin/base/Memo.java
index 89be20b8..30ad6771 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Memo.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Memo.java
@@ -5,13 +5,14 @@
/**
*
- *
* 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.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.
- * MemoHash memo = new MemoHash("4142434445");
- * memo.getHexValue(); // 4142434445000000000000000000000000000000000000000000000000000000
- * memo.getTrimmedHexValue(); // 4142434445
- *
- */
- public String getHexValue() {
- return new String(Hex.encodeHex(this.bytes));
- }
+ /**
+ *
+ * MemoHash memo = new MemoHash("4142434445");
+ * memo.getHexValue(); // 4142434445000000000000000000000000000000000000000000000000000000
+ * memo.getTrimmedHexValue(); // 4142434445
+ *
+ */
+ public String getHexValue() {
+ return new String(Hex.encodeHex(this.bytes));
+ }
- /**
- *
- * MemoHash memo = new MemoHash("4142434445");
- * memo.getHexValue(); // 4142434445000000000000000000000000000000000000000000000000000000
- * memo.getTrimmedHexValue(); // 4142434445
- *
- */
- public String getTrimmedHexValue() {
- return this.getHexValue().split("00")[0];
- }
+ /**
+ *
+ * MemoHash memo = new MemoHash("4142434445");
+ * memo.getHexValue(); // 4142434445000000000000000000000000000000000000000000000000000000
+ * memo.getTrimmedHexValue(); // 4142434445
+ *
+ */
+ public String getTrimmedHexValue() {
+ return this.getHexValue().split("00")[0];
+ }
- @Override
- abstract kin.base.xdr.Memo toXdr();
+ @Override
+ abstract kin.base.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 Arrays.equals(bytes, that.bytes);
- }
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ MemoHashAbstract that = (MemoHashAbstract) o;
+ return Arrays.equals(bytes, that.bytes);
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoId.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoId.java
index 7ef4c75d..53703b45 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoId.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoId.java
@@ -7,35 +7,35 @@
* Represents MEMO_ID.
*/
public class MemoId extends Memo {
- private long id;
+ private long id;
- public MemoId(long id) {
- if (id < 0) {
- throw new IllegalArgumentException("id must be a positive number");
+ public MemoId(long id) {
+ if (id < 0) {
+ throw new IllegalArgumentException("id must be a positive number");
+ }
+ this.id = id;
}
- this.id = id;
- }
- public long getId() {
- return id;
- }
+ public long getId() {
+ return id;
+ }
- @Override
- kin.base.xdr.Memo toXdr() {
- kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
- memo.setDiscriminant(MemoType.MEMO_ID);
- Uint64 idXdr = new Uint64();
- idXdr.setUint64(id);
- memo.setId(idXdr);
- return memo;
- }
+ @Override
+ kin.base.xdr.Memo toXdr() {
+ kin.base.xdr.Memo memo = new kin.base.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;
- }
+ @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/kin-sdk/kin-base/src/main/java/kin/base/MemoNone.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoNone.java
index b060919c..8c57b190 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoNone.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoNone.java
@@ -6,17 +6,17 @@
* Represents MEMO_NONE.
*/
public class MemoNone extends Memo {
- @Override
- kin.base.xdr.Memo toXdr() {
- kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
- memo.setDiscriminant(MemoType.MEMO_NONE);
- return memo;
- }
+ @Override
+ kin.base.xdr.Memo toXdr() {
+ kin.base.xdr.Memo memo = new kin.base.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;
- }
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ return true;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoReturnHash.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoReturnHash.java
index 4ab4d208..caefda5b 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoReturnHash.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoReturnHash.java
@@ -8,23 +8,23 @@
* Represents MEMO_RETURN.
*/
public class MemoReturnHash extends MemoHashAbstract {
- public MemoReturnHash(byte[] bytes) {
- super(bytes);
- }
+ public MemoReturnHash(byte[] bytes) {
+ super(bytes);
+ }
- public MemoReturnHash(String hexString) throws DecoderException {
- super(hexString);
- }
+ public MemoReturnHash(String hexString) throws DecoderException {
+ super(hexString);
+ }
- @Override
- Memo toXdr() {
- kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
- memo.setDiscriminant(MemoType.MEMO_RETURN);
+ @Override
+ Memo toXdr() {
+ kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
+ memo.setDiscriminant(MemoType.MEMO_RETURN);
- kin.base.xdr.Hash hash = new kin.base.xdr.Hash();
- hash.setHash(bytes);
+ kin.base.xdr.Hash hash = new kin.base.xdr.Hash();
+ hash.setHash(bytes);
- memo.setHash(hash);
- return memo;
- }
+ memo.setHash(hash);
+ return memo;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoText.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoText.java
index 4912794e..566c791d 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoText.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoText.java
@@ -1,55 +1,56 @@
package kin.base;
-import static kin.base.Util.CHARSET_UTF8;
-import static kin.base.Util.checkNotNull;
-
import java.io.UnsupportedEncodingException;
+
import kin.base.xdr.MemoType;
+import static kin.base.Util.CHARSET_UTF8;
+import static kin.base.Util.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 = 0;
- try {
- length = text.getBytes(CHARSET_UTF8).length;
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
+ private String text;
+
+ public MemoText(String text) {
+ this.text = checkNotNull(text, "text cannot be null");
+
+ int length = 0;
+ try {
+ length = text.getBytes(CHARSET_UTF8).length;
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ if (length > 28) {
+ throw new MemoTooLongException("text must be <= 28 bytes. length=" + String.valueOf(length));
+ }
}
- if (length > 28) {
- throw new MemoTooLongException("text must be <= 28 bytes. length=" + String.valueOf(length));
+
+ public String getText() {
+ return text;
}
- }
-
- public String getText() {
- return text;
- }
-
- @Override
- kin.base.xdr.Memo toXdr() {
- kin.base.xdr.Memo memo = new kin.base.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;
- if (text == null && memoText.text == null) {
- return true;
+
+ @Override
+ kin.base.xdr.Memo toXdr() {
+ kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
+ memo.setDiscriminant(MemoType.MEMO_TEXT);
+ memo.setText(text);
+ return memo;
}
- if (text != null && memoText!= null) {
- return text.equals(memoText.text);
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ MemoText memoText = (MemoText) o;
+ if (text == null && memoText.text == null) {
+ return true;
+ }
+ if (text != null && memoText != null) {
+ return text.equals(memoText.text);
+ }
+ return false;
}
- return false;
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoTooLongException.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoTooLongException.java
index aaca3190..e4929c12 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoTooLongException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoTooLongException.java
@@ -2,6 +2,7 @@
/**
* Indicates that value passed to Memo
+ *
* @see Memo
*/
public class MemoTooLongException extends RuntimeException {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Network.java b/kin-sdk/kin-base/src/main/java/kin/base/Network.java
index a96bf8ed..8407fb0e 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Network.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Network.java
@@ -1,10 +1,10 @@
package kin.base;
+import java.io.UnsupportedEncodingException;
+
import static kin.base.Util.CHARSET_UTF8;
import static kin.base.Util.checkNotNull;
-import java.io.UnsupportedEncodingException;
-
/**
* Network class is used to specify which Stellar network you want to use.
* Each network has a networkPassphrase which is hashed to
@@ -13,75 +13,75 @@
* {@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 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;
+ 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");
- }
+ /**
+ * 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 passphrase
+ */
+ public String getNetworkPassphrase() {
+ return networkPassphrase;
+ }
- /**
- * Returns network id (SHA-256 hashed networkPassphrase).
- */
- public byte[] getNetworkId() {
- try {
- return Util.hash(current.getNetworkPassphrase().getBytes(CHARSET_UTF8));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- return null;
+ /**
+ * Returns network id (SHA-256 hashed networkPassphrase).
+ */
+ public byte[] getNetworkId() {
+ try {
+ return Util.hash(current.getNetworkPassphrase().getBytes(CHARSET_UTF8));
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ return null;
+ }
}
- }
- /**
- * Returns currently used Network object.
- */
- public static Network current() {
- return current;
- }
+ /**
+ * 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 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(getPublicNetwork());
- }
+ /**
+ * Use Stellar Public Network
+ */
+ public static void usePublicNetwork() {
+ Network.use(getPublicNetwork());
+ }
- /**
- * Use Stellar Test Network.
- */
- public static void useTestNetwork() {
- Network.use(getTestNetwork());
- }
+ /**
+ * Use Stellar Test Network.
+ */
+ public static void useTestNetwork() {
+ Network.use(getTestNetwork());
+ }
- public static Network getPublicNetwork() {
- return new Network(PUBLIC);
- }
+ public static Network getPublicNetwork() {
+ return new Network(PUBLIC);
+ }
- public static Network getTestNetwork() {
- return new Network(TESTNET);
- }
+ public static Network getTestNetwork() {
+ return new Network(TESTNET);
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/NoNetworkSelectedException.java b/kin-sdk/kin-base/src/main/java/kin/base/NoNetworkSelectedException.java
index abe0945a..a35fd09d 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/NoNetworkSelectedException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/NoNetworkSelectedException.java
@@ -4,7 +4,7 @@
* 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.");
- }
+ public NoNetworkSelectedException() {
+ super("No network selected. Use `Network.use`, `Network.usePublicNetwork` or `Network.useTestNetwork` helper methods to select network.");
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Operation.java b/kin-sdk/kin-base/src/main/java/kin/base/Operation.java
index f462af62..a07246cf 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Operation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Operation.java
@@ -1,130 +1,135 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
+
import kin.base.codec.Base64;
import kin.base.xdr.AccountID;
import kin.base.xdr.XdrDataOutputStream;
+import static kin.base.Util.checkNotNull;
+
/**
* Abstract class for operations.
*/
public abstract class Operation {
- Operation() {}
-
- private KeyPair mSourceAccount;
+ Operation() {
+ }
- private static final BigDecimal ONE = new BigDecimal(10).pow(5);
+ private KeyPair mSourceAccount;
- protected static long toXdrAmount(String value) {
- value = checkNotNull(value, "value cannot be null");
- BigDecimal amount = new BigDecimal(value).multiply(Operation.ONE);
- return amount.longValueExact();
- }
+ private static final BigDecimal ONE = new BigDecimal(10).pow(5);
- protected static String fromXdrAmount(long value) {
- BigDecimal amount = new BigDecimal(value).divide(Operation.ONE);
- return amount.toPlainString();
- }
+ protected static long toXdrAmount(String value) {
+ value = checkNotNull(value, "value cannot be null");
+ BigDecimal amount = new BigDecimal(value).multiply(Operation.ONE);
+ return amount.longValueExact();
+ }
- /**
- * Generates Operation XDR object.
- */
- public kin.base.xdr.Operation toXdr() {
- kin.base.xdr.Operation xdr = new kin.base.xdr.Operation();
- if (getSourceAccount() != null) {
- AccountID sourceAccount = new AccountID();
- sourceAccount.setAccountID(getSourceAccount().getXdrPublicKey());
- xdr.setSourceAccount(sourceAccount);
+ protected static String fromXdrAmount(long value) {
+ BigDecimal amount = new BigDecimal(value).divide(Operation.ONE);
+ return amount.toPlainString();
}
- xdr.setBody(toOperationBody());
- return xdr;
- }
- /**
- * Returns base64-encoded Operation XDR object.
- */
- public String toXdrBase64() {
- try {
- kin.base.xdr.Operation operation = this.toXdr();
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream);
- kin.base.xdr.Operation.encode(xdrOutputStream, operation);
- Base64 base64Codec = new Base64();
- return base64Codec.encodeAsString(outputStream.toByteArray());
- } catch (IOException e) {
- throw new AssertionError(e);
+ /**
+ * Generates Operation XDR object.
+ */
+ public kin.base.xdr.Operation toXdr() {
+ kin.base.xdr.Operation xdr = new kin.base.xdr.Operation();
+ if (getSourceAccount() != null) {
+ AccountID sourceAccount = new AccountID();
+ sourceAccount.setAccountID(getSourceAccount().getXdrPublicKey());
+ xdr.setSourceAccount(sourceAccount);
+ }
+ xdr.setBody(toOperationBody());
+ return xdr;
}
- }
- /**
- * Returns new Operation object from Operation XDR object.
- * @param xdr XDR object
- */
- public static Operation fromXdr(kin.base.xdr.Operation xdr) {
- kin.base.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;
- default:
- throw new RuntimeException("Unknown operation body " + body.getDiscriminant());
+ /**
+ * Returns base64-encoded Operation XDR object.
+ */
+ public String toXdrBase64() {
+ try {
+ kin.base.xdr.Operation operation = this.toXdr();
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream);
+ kin.base.xdr.Operation.encode(xdrOutputStream, operation);
+ Base64 base64Codec = new Base64();
+ return base64Codec.encodeAsString(outputStream.toByteArray());
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
}
- if (xdr.getSourceAccount() != null) {
- operation.setSourceAccount(KeyPair.fromXdrPublicKey(xdr.getSourceAccount().getAccountID()));
+
+ /**
+ * Returns new Operation object from Operation XDR object.
+ *
+ * @param xdr XDR object
+ */
+ public static Operation fromXdr(kin.base.xdr.Operation xdr) {
+ kin.base.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;
+ default:
+ throw new RuntimeException("Unknown operation body " + body.getDiscriminant());
+ }
+ if (xdr.getSourceAccount() != null) {
+ operation.setSourceAccount(KeyPair.fromXdrPublicKey(xdr.getSourceAccount().getAccountID()));
+ }
+ return operation;
}
- return operation;
- }
- /**
- * Returns operation source account.
- */
- public KeyPair getSourceAccount() {
- return mSourceAccount;
- }
+ /**
+ * 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");
- }
+ /**
+ * 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 kin.base.xdr.Operation.OperationBody toOperationBody();
+ /**
+ * Generates OperationBody XDR object
+ *
+ * @return OperationBody XDR object
+ */
+ abstract kin.base.xdr.Operation.OperationBody toOperationBody();
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/PathPaymentOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/PathPaymentOperation.java
index d79dac81..4a45fc96 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/PathPaymentOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/PathPaymentOperation.java
@@ -1,193 +1,198 @@
package kin.base;
-import static kin.base.Util.checkArgument;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.AccountID;
import kin.base.xdr.Int64;
import kin.base.xdr.OperationType;
import kin.base.xdr.PathPaymentOp;
+import static kin.base.Util.checkArgument;
+import static kin.base.Util.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
- kin.base.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
- kin.base.xdr.Asset[] path = new kin.base.xdr.Asset[this.path.length];
- for (int i = 0; i < this.path.length; i++) {
- path[i] = this.path[i].toXdr();
- }
- op.setPath(path);
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.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]);
- }
+ 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;
}
/**
- * 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.
+ * Account that receives the payment.
*/
- 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");
+ public KeyPair getDestination() {
+ return destination;
}
/**
- * 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.
+ * The asset the destination account receives.
*/
- 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;
+ public Asset getDestAsset() {
+ return destAsset;
}
/**
- * Sets the source account for this operation.
- * @param sourceAccount The operation's source account.
- * @return Builder object so you can chain methods.
+ * The amount of destination asset the destination account receives.
*/
- public Builder setSourceAccount(KeyPair sourceAccount) {
- mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null");
- return this;
+ 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
+ kin.base.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
+ kin.base.xdr.Asset[] path = new kin.base.xdr.Asset[this.path.length];
+ for (int i = 0; i < this.path.length; i++) {
+ path[i] = this.path[i].toXdr();
+ }
+ op.setPath(path);
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.PATH_PAYMENT);
+ body.setPathPaymentOp(op);
+ return body;
}
/**
- * Builds an operation
+ * Builds PathPayment operation.
+ *
+ * @see PathPaymentOperation
*/
- public PathPaymentOperation build() {
- PathPaymentOperation operation = new PathPaymentOperation(sendAsset, sendMax, destination,
- destAsset, destAmount, path);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ 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/kin-sdk/kin-base/src/main/java/kin/base/PaymentOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/PaymentOperation.java
index 29aaee65..584424f7 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/PaymentOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/PaymentOperation.java
@@ -1,123 +1,128 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.AccountID;
import kin.base.xdr.Int64;
import kin.base.xdr.OperationType;
import kin.base.xdr.PaymentOp;
+import static kin.base.Util.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
- kin.base.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);
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.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;
+ 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");
+ }
/**
- * Construct a new PaymentOperation builder from a PaymentOp XDR.
- * @param op {@link PaymentOp}
+ * Account that receives the payment.
*/
- Builder(PaymentOp op) {
- destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID());
- asset = Asset.fromXdr(op.getAsset());
- amount = Operation.fromXdrAmount(op.getAmount().getInt64().longValue());
+ public KeyPair getDestination() {
+ return destination;
}
/**
- * 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.
+ * Asset to send to the destination account.
*/
- public Builder(KeyPair destination, Asset asset, String amount) {
- this.destination = destination;
- this.asset = asset;
- this.amount = amount;
+ public Asset getAsset() {
+ return asset;
}
/**
- * Sets the source account for this operation.
- * @param account The operation's source account.
- * @return Builder object so you can chain methods.
+ * Amount of the asset to send.
*/
- public Builder setSourceAccount(KeyPair account) {
- mSourceAccount = account;
- return this;
+ public String getAmount() {
+ return amount;
+ }
+
+ @Override
+ kin.base.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);
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.PAYMENT);
+ body.setPaymentOp(op);
+ return body;
}
/**
- * Builds an operation
+ * Builds Payment operation.
+ *
+ * @see PathPaymentOperation
*/
- public PaymentOperation build() {
- PaymentOperation operation = new PaymentOperation(destination, asset, amount);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ 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/kin-sdk/kin-base/src/main/java/kin/base/Price.java b/kin-sdk/kin-base/src/main/java/kin/base/Price.java
index e3fa8830..a7d7ee8b 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Price.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Price.java
@@ -1,13 +1,15 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.annotations.SerializedName;
+
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
+
import kin.base.xdr.Int32;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents Price. Price in Stellar is represented as a fraction.
*/
@@ -19,6 +21,7 @@ public class Price {
/**
* Create a new price. Price in Stellar is represented as a fraction.
+ *
* @param n numerator
* @param d denominator
*/
@@ -45,6 +48,7 @@ public int getDenominator() {
* 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) {
@@ -75,8 +79,8 @@ public static Price fromString(String price) {
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];
+ BigDecimal n = fractions.get(fractions.size() - 1)[0];
+ BigDecimal d = fractions.get(fractions.size() - 1)[1];
return new Price(n.intValue(), d.intValue());
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Server.java b/kin-sdk/kin-base/src/main/java/kin/base/Server.java
index 6a0228ad..cf99e970 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Server.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Server.java
@@ -1,12 +1,11 @@
package kin.base;
-import android.net.Uri;
-import android.net.Uri.Builder;
-import android.text.TextUtils;
import java.io.IOException;
+import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.concurrent.TimeUnit;
+import java.net.URL;
+
import kin.base.requests.AccountsRequestBuilder;
import kin.base.requests.EffectsRequestBuilder;
import kin.base.requests.LedgersRequestBuilder;
@@ -20,7 +19,7 @@
import kin.base.responses.GsonSingleton;
import kin.base.responses.SubmitTransactionResponse;
import okhttp3.FormBody;
-import okhttp3.Interceptor;
+import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@@ -34,7 +33,6 @@ public class Server {
private static final int TEMPORARY_REDIRECT = 307;
private static final String LOCATION_HEADER = "Location";
- private static final String KIN_SDK_ANDROID_VERSION_HEADER = "kin-sdk-android-version";
private URI serverURI;
@@ -55,23 +53,19 @@ public Server(String uri) {
* ed25519PublicKey {@link kin.base.xdr.SignerKey} from
* a {@link KeyPair}
+ *
* @param keyPair
* @return kin.base.xdr.SignerKey
*/
@@ -24,6 +25,7 @@ public static SignerKey ed25519PublicKey(KeyPair keyPair) {
/**
* Create sha256Hash {@link kin.base.xdr.SignerKey} from
* a sha256 hash of a preimage.
+ *
* @param hash
* @return kin.base.xdr.SignerKey
*/
@@ -41,6 +43,7 @@ public static SignerKey sha256Hash(byte[] hash) {
/**
* Create preAuthTx {@link kin.base.xdr.SignerKey} from
* a {@link kin.base.xdr.Transaction} hash.
+ *
* @param tx
* @return kin.base.xdr.SignerKey
*/
@@ -58,6 +61,7 @@ public static SignerKey preAuthTx(Transaction tx) {
/**
* Create preAuthTx {@link kin.base.xdr.SignerKey} from
* a transaction hash.
+ *
* @param hash
* @return kin.base.xdr.SignerKey
*/
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/StrKey.java b/kin-sdk/kin-base/src/main/java/kin/base/StrKey.java
index 6967b1b9..625c7926 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/StrKey.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/StrKey.java
@@ -3,18 +3,21 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
+
import kin.base.codec.Base32;
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
+ 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;
}
@@ -96,9 +99,9 @@ protected static byte[] decodeCheck(VersionByte versionByte, char[] encoded) {
Base32 base32Codec = new Base32();
byte[] decoded = base32Codec.decode(bytes);
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);
+ 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");
@@ -141,8 +144,8 @@ protected static byte[] calculateChecksum(byte[] bytes) {
}
// little-endian
- return new byte[] {
- (byte)crc,
- (byte)(crc >>> 8)};
+ return new byte[]{
+ (byte) crc,
+ (byte) (crc >>> 8)};
}
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/TimeBounds.java b/kin-sdk/kin-base/src/main/java/kin/base/TimeBounds.java
index f324b6fb..ac9e129a 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/TimeBounds.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/TimeBounds.java
@@ -4,63 +4,64 @@
/**
* Transaction instance from previously build TransactionEnvelope
+ *
+ * @param envelope Base-64 encoded TransactionEnvelope
+ * @return
+ * @throws IOException
*/
- 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;
+ public static Transaction fromEnvelopeXdr(String envelope) throws IOException {
+ TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(Util.createXdrDataInputStream(envelope));
+ return fromEnvelopeXdr(transactionEnvelope);
}
-
+
/**
- * Adds a time-bounds to this transaction.
- * @param timeBounds
- * @return Builder object so you can chain methods.
- * @see TimeBounds
+ * Creates a Transaction instance from previously build TransactionEnvelope
+ *
+ * @param envelope Base-64 encoded TransactionEnvelope
+ * @return
*/
- 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;
+ public static Transaction fromEnvelopeXdr(TransactionEnvelope envelope) {
+ kin.base.xdr.Transaction tx = envelope.getTx();
+ int mFee = tx.getFee().getUint32();
+ KeyPair mSourceAccount = KeyPair.fromXdrPublicKey(tx.getSourceAccount().getAccountID());
+ Long mSequenceNumber = tx.getSeqNum().getSequenceNumber().getUint64();
+ 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;
}
/**
- * Builds a transaction. It will increment sequence number of the source account.
+ * Builds a new Transaction object.
*/
- public Transaction build() {
- Operation[] operations = new Operation[mOperations.size()];
- operations = mOperations.toArray(operations);
- Transaction transaction = new Transaction(mSourceAccount.getKeypair(), fee, mSourceAccount.getIncrementedSequenceNumber(), operations, mMemo, mTimeBounds);
- // Increment sequence number when there were no exceptions when creating a transaction
- mSourceAccount.incrementSequenceNumber();
- return transaction;
+ public static class Builder {
+ private final TransactionBuilderAccount mSourceAccount;
+ private int fee;
+ private Memo mMemo;
+ private TimeBounds mTimeBounds;
+ Listdata.
- * @param data
- */
- 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");
+ /**
+ * Returns SHA-256 hash of data.
+ *
+ * @param data
+ */
+ 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 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);
- }
+ /**
+ * 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];
- }
+ /**
+ * Remove zeros from the end of bytes array.
+ *
+ * @param bytes
+ */
+ static String paddedByteArrayToString(byte[] bytes) {
+ return new String(bytes).split("\0")[0];
+ }
- public static
* When encoding the line length is 0 (no chunking). *
- * */ public Base32() { this(false); @@ -182,6 +180,7 @@ public Base32() { ** When encoding the line length is 0 (no chunking). *
+ * * @param useHex iftrue then use Base32 Hex alphabet
*/
public Base32(boolean useHex) {
@@ -194,9 +193,8 @@ public Base32(boolean useHex) {
* When encoding the line length is given in the constructor, the line separator is CRLF.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
*/
public Base32(int lineLength) {
this(lineLength, CHUNK_SEPARATOR);
@@ -211,13 +209,10 @@ public Base32(int lineLength) {
* Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
- * @param lineSeparator
- * Each line of encoded data will end with this sequence of bytes.
- * @throws IllegalArgumentException
- * The provided lineSeparator included some Base32 characters. That's not going to work!
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineSeparator Each line of encoded data will end with this sequence of bytes.
+ * @throws IllegalArgumentException The provided lineSeparator included some Base32 characters. That's not going to work!
*/
public Base32(int lineLength, byte[] lineSeparator) {
this(lineLength, lineSeparator, false);
@@ -232,21 +227,18 @@ public Base32(int lineLength, byte[] lineSeparator) {
* Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
- * @param lineSeparator
- * Each line of encoded data will end with this sequence of bytes.
- * @param useHex if true, then use Base32 Hex alphabet, otherwise use Base32 alphabet
- * @throws IllegalArgumentException
- * The provided lineSeparator included some Base32 characters. That's not going to work!
- * Or the lineLength > 0 and lineSeparator is null.
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineSeparator Each line of encoded data will end with this sequence of bytes.
+ * @param useHex if true, then use Base32 Hex alphabet, otherwise use Base32 alphabet
+ * @throws IllegalArgumentException The provided lineSeparator included some Base32 characters. That's not going to work!
+ * Or the lineLength > 0 and lineSeparator is null.
*/
public Base32(int lineLength, byte[] lineSeparator, boolean useHex) {
super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK,
lineLength,
lineSeparator == null ? 0 : lineSeparator.length);
- if (useHex){
+ if (useHex) {
this.encodeTable = HEX_ENCODE_TABLE;
this.decodeTable = HEX_DECODE_TABLE;
} else {
@@ -255,7 +247,7 @@ public Base32(int lineLength, byte[] lineSeparator, boolean useHex) {
}
if (lineLength > 0) {
if (lineSeparator == null) {
- throw new IllegalArgumentException("lineLength "+lineLength+" > 0, but lineSeparator is null");
+ throw new IllegalArgumentException("lineLength " + lineLength + " > 0, but lineSeparator is null");
}
// Must be done after initializing the tables
if (containsAlphabetOrPad(lineSeparator)) {
@@ -284,13 +276,9 @@ public Base32(int lineLength, byte[] lineSeparator, boolean useHex) {
* garbage-out philosophy: it will not check the provided data for validity.
*
*
- * @param in
- * byte[] array of ascii data to Base32 decode.
- * @param inPos
- * Position to start reading data from.
- * @param inAvail
- * Amount of bytes available from input for encoding.
- *
+ * @param in byte[] array of ascii data to Base32 decode.
+ * @param inPos Position to start reading data from.
+ * @param inAvail Amount of bytes available from input for encoding.
*/
void decode(byte[] in, int inPos, int inAvail) { // package protected for access from I/O streams
if (eof) {
@@ -310,7 +298,7 @@ void decode(byte[] in, int inPos, int inAvail) { // package protected for access
if (b >= 0 && b < this.decodeTable.length) {
int result = this.decodeTable[b];
if (result >= 0) {
- modulus = (modulus+1) % BYTES_PER_ENCODED_BLOCK;
+ modulus = (modulus + 1) % BYTES_PER_ENCODED_BLOCK;
bitWorkArea = (bitWorkArea << BITS_PER_ENCODED_BYTE) + result; // collect decoded bytes
if (modulus == 0) { // we can output the 5 bytes
buffer[pos++] = (byte) ((bitWorkArea >> 32) & MASK_8BITS);
@@ -332,30 +320,30 @@ void decode(byte[] in, int inPos, int inAvail) { // package protected for access
// we ignore partial bytes, i.e. only multiples of 8 count
switch (modulus) {
- case 2 : // 10 bits, drop 2 and output one byte
+ case 2: // 10 bits, drop 2 and output one byte
buffer[pos++] = (byte) ((bitWorkArea >> 2) & MASK_8BITS);
break;
- case 3 : // 15 bits, drop 7 and output 1 byte
+ case 3: // 15 bits, drop 7 and output 1 byte
buffer[pos++] = (byte) ((bitWorkArea >> 7) & MASK_8BITS);
break;
- case 4 : // 20 bits = 2*8 + 4
+ case 4: // 20 bits = 2*8 + 4
bitWorkArea = bitWorkArea >> 4; // drop 4 bits
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
break;
- case 5 : // 25bits = 3*8 + 1
+ case 5: // 25bits = 3*8 + 1
bitWorkArea = bitWorkArea >> 1;
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
break;
- case 6 : // 30bits = 3*8 + 6
+ case 6: // 30bits = 3*8 + 6
bitWorkArea = bitWorkArea >> 6;
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
break;
- case 7 : // 35 = 4*8 +3
+ case 7: // 35 = 4*8 +3
bitWorkArea = bitWorkArea >> 3;
buffer[pos++] = (byte) ((bitWorkArea >> 24) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
@@ -373,12 +361,9 @@ void decode(byte[] in, int inPos, int inAvail) { // package protected for access
* remaining bytes (if not multiple of 5).
*
*
- * @param in
- * byte[] array of binary data to Base32 encode.
- * @param inPos
- * Position to start reading data from.
- * @param inAvail
- * Amount of bytes available from input for encoding.
+ * @param in byte[] array of binary data to Base32 encode.
+ * @param inPos Position to start reading data from.
+ * @param inAvail Amount of bytes available from input for encoding.
*/
void encode(byte[] in, int inPos, int inAvail) { // package protected for access from I/O streams
if (eof) {
@@ -394,9 +379,9 @@ void encode(byte[] in, int inPos, int inAvail) { // package protected for access
ensureBufferSize(encodeSize);
int savedPos = pos;
switch (modulus) { // % 5
- case 1 : // Only 1 octet; take top 5 bits then remainder
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 3) & MASK_5BITS]; // 8-1*5 = 3
- buffer[pos++] = encodeTable[(int)(bitWorkArea << 2) & MASK_5BITS]; // 5-3=2
+ case 1: // Only 1 octet; take top 5 bits then remainder
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 3) & MASK_5BITS]; // 8-1*5 = 3
+ buffer[pos++] = encodeTable[(int) (bitWorkArea << 2) & MASK_5BITS]; // 5-3=2
buffer[pos++] = PAD;
buffer[pos++] = PAD;
buffer[pos++] = PAD;
@@ -405,61 +390,61 @@ void encode(byte[] in, int inPos, int inAvail) { // package protected for access
buffer[pos++] = PAD;
break;
- case 2 : // 2 octets = 16 bits to use
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 11) & MASK_5BITS]; // 16-1*5 = 11
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 6) & MASK_5BITS]; // 16-2*5 = 6
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 1) & MASK_5BITS]; // 16-3*5 = 1
- buffer[pos++] = encodeTable[(int)(bitWorkArea << 4) & MASK_5BITS]; // 5-1 = 4
+ case 2: // 2 octets = 16 bits to use
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 11) & MASK_5BITS]; // 16-1*5 = 11
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 6) & MASK_5BITS]; // 16-2*5 = 6
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 1) & MASK_5BITS]; // 16-3*5 = 1
+ buffer[pos++] = encodeTable[(int) (bitWorkArea << 4) & MASK_5BITS]; // 5-1 = 4
buffer[pos++] = PAD;
buffer[pos++] = PAD;
buffer[pos++] = PAD;
buffer[pos++] = PAD;
break;
- case 3 : // 3 octets = 24 bits to use
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 19) & MASK_5BITS]; // 24-1*5 = 19
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 14) & MASK_5BITS]; // 24-2*5 = 14
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 9) & MASK_5BITS]; // 24-3*5 = 9
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 4) & MASK_5BITS]; // 24-4*5 = 4
- buffer[pos++] = encodeTable[(int)(bitWorkArea << 1) & MASK_5BITS]; // 5-4 = 1
+ case 3: // 3 octets = 24 bits to use
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 19) & MASK_5BITS]; // 24-1*5 = 19
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 14) & MASK_5BITS]; // 24-2*5 = 14
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 9) & MASK_5BITS]; // 24-3*5 = 9
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 4) & MASK_5BITS]; // 24-4*5 = 4
+ buffer[pos++] = encodeTable[(int) (bitWorkArea << 1) & MASK_5BITS]; // 5-4 = 1
buffer[pos++] = PAD;
buffer[pos++] = PAD;
buffer[pos++] = PAD;
break;
- case 4 : // 4 octets = 32 bits to use
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 27) & MASK_5BITS]; // 32-1*5 = 27
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 22) & MASK_5BITS]; // 32-2*5 = 22
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 17) & MASK_5BITS]; // 32-3*5 = 17
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 12) & MASK_5BITS]; // 32-4*5 = 12
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 7) & MASK_5BITS]; // 32-5*5 = 7
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 2) & MASK_5BITS]; // 32-6*5 = 2
- buffer[pos++] = encodeTable[(int)(bitWorkArea << 3) & MASK_5BITS]; // 5-2 = 3
+ case 4: // 4 octets = 32 bits to use
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 27) & MASK_5BITS]; // 32-1*5 = 27
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 22) & MASK_5BITS]; // 32-2*5 = 22
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 17) & MASK_5BITS]; // 32-3*5 = 17
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 12) & MASK_5BITS]; // 32-4*5 = 12
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 7) & MASK_5BITS]; // 32-5*5 = 7
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 2) & MASK_5BITS]; // 32-6*5 = 2
+ buffer[pos++] = encodeTable[(int) (bitWorkArea << 3) & MASK_5BITS]; // 5-2 = 3
buffer[pos++] = PAD;
break;
}
currentLinePos += pos - savedPos; // keep track of current line position
// if currentPos == 0 we are at the start of a line, so don't add CRLF
- if (lineLength > 0 && currentLinePos > 0){ // add chunk separator if required
+ if (lineLength > 0 && currentLinePos > 0) { // add chunk separator if required
System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);
pos += lineSeparator.length;
}
} else {
for (int i = 0; i < inAvail; i++) {
ensureBufferSize(encodeSize);
- modulus = (modulus+1) % BYTES_PER_UNENCODED_BLOCK;
+ modulus = (modulus + 1) % BYTES_PER_UNENCODED_BLOCK;
int b = in[inPos++];
if (b < 0) {
b += 256;
}
bitWorkArea = (bitWorkArea << 8) + b; // BITS_PER_BYTE
if (0 == modulus) { // we have enough bytes to create our output
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 35) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 30) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 25) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 20) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 15) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 10) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 5) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)bitWorkArea & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 35) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 30) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 25) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 20) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 15) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 10) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 5) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) bitWorkArea & MASK_5BITS];
currentLinePos += BYTES_PER_ENCODED_BLOCK;
if (lineLength > 0 && lineLength <= currentLinePos) {
System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);
@@ -474,8 +459,7 @@ void encode(byte[] in, int inPos, int inAvail) { // package protected for access
/**
* Returns whether or not the octet is in the Base32 alphabet.
*
- * @param octet
- * The value to test
+ * @param octet The value to test
* @return true if the value is defined in the the Base32 alphabet false otherwise.
*/
public boolean isInAlphabet(byte octet) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Base64.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Base64.java
index 93e34ca0..c8acfc84 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Base64.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Base64.java
@@ -59,10 +59,10 @@
* This class is not thread-safe. Each thread should use its own instance.
*
*
- * @see RFC 2045
* @author Apache Software Foundation
- * @since 1.0
* @version $Revision$
+ * @see RFC 2045
+ * @since 1.0
*/
public class Base64 extends BaseNCodec {
@@ -89,7 +89,7 @@ public class Base64 extends BaseNCodec {
/**
* This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
* equivalents as specified in Table 1 of RFC 2045.
- *
+ * * Thanks to "commons" project in ws.apache.org for this code. * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ */ @@ -118,10 +118,10 @@ public class Base64 extends BaseNCodec { * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in * Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64 * alphabet but fall within the bounds of the array are translated to -1. - * + *
* Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit). - * + *
* Thanks to "commons" project in ws.apache.org for this code. * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ */ @@ -138,7 +138,9 @@ public class Base64 extends BaseNCodec { /** * Base64 uses 6-bit fields. */ - /** Mask used to extract 6 bits, used when encoding */ + /** + * Mask used to extract 6 bits, used when encoding + */ private static final int MASK_6BITS = 0x3f; // The static final fields above are used for the original static byte[] methods on Base64. @@ -202,9 +204,8 @@ public Base64() { * When decoding all variants are supported. *
* - * @param urlSafe - * iftrue, URL-safe encoding is used. In most cases this should be set to
- * false.
+ * @param urlSafe if true, URL-safe encoding is used. In most cases this should be set to
+ * false.
* @since 1.4
*/
public Base64(boolean urlSafe) {
@@ -224,9 +225,8 @@ public Base64(boolean urlSafe) {
* When decoding all variants are supported.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
* @since 1.4
*/
public Base64(int lineLength) {
@@ -246,13 +246,10 @@ public Base64(int lineLength) {
* When decoding all variants are supported.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
- * @param lineSeparator
- * Each line of encoded data will end with this sequence of bytes.
- * @throws IllegalArgumentException
- * Thrown when the provided lineSeparator included some base64 characters.
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineSeparator Each line of encoded data will end with this sequence of bytes.
+ * @throws IllegalArgumentException Thrown when the provided lineSeparator included some base64 characters.
* @since 1.4
*/
public Base64(int lineLength, byte[] lineSeparator) {
@@ -272,16 +269,12 @@ public Base64(int lineLength, byte[] lineSeparator) {
* When decoding all variants are supported.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
- * @param lineSeparator
- * Each line of encoded data will end with this sequence of bytes.
- * @param urlSafe
- * Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
- * operations. Decoding seamlessly handles both modes.
- * @throws IllegalArgumentException
- * The provided lineSeparator included some base64 characters. That's not going to work!
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineSeparator Each line of encoded data will end with this sequence of bytes.
+ * @param urlSafe Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
+ * operations. Decoding seamlessly handles both modes.
+ * @throws IllegalArgumentException The provided lineSeparator included some base64 characters. That's not going to work!
* @since 1.4
*/
public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
@@ -295,7 +288,7 @@ public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
String sep = StringUtils.newStringUtf8(lineSeparator);
throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
}
- if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE
+ if (lineLength > 0) { // null line-sep forces no chunking rather than throwing IAE
this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
this.lineSeparator = new byte[lineSeparator.length];
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
@@ -332,12 +325,9 @@ public boolean isUrlSafe() {
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*
*
- * @param in
- * byte[] array of binary data to base64 encode.
- * @param inPos
- * Position to start reading data from.
- * @param inAvail
- * Amount of bytes available from input for encoding.
+ * @param in byte[] array of binary data to base64 encode.
+ * @param inPos Position to start reading data from.
+ * @param inAvail Amount of bytes available from input for encoding.
*/
void encode(byte[] in, int inPos, int inAvail) {
if (eof) {
@@ -353,7 +343,7 @@ void encode(byte[] in, int inPos, int inAvail) {
ensureBufferSize(encodeSize);
int savedPos = pos;
switch (modulus) { // 0-2
- case 1 : // 8 bits = 6 + 2
+ case 1: // 8 bits = 6 + 2
buffer[pos++] = encodeTable[(bitWorkArea >> 2) & MASK_6BITS]; // top 6 bits
buffer[pos++] = encodeTable[(bitWorkArea << 4) & MASK_6BITS]; // remaining 2
// URL-SAFE skips the padding to further reduce size.
@@ -363,7 +353,7 @@ void encode(byte[] in, int inPos, int inAvail) {
}
break;
- case 2 : // 16 bits = 6 + 6 + 4
+ case 2: // 16 bits = 6 + 6 + 4
buffer[pos++] = encodeTable[(bitWorkArea >> 10) & MASK_6BITS];
buffer[pos++] = encodeTable[(bitWorkArea >> 4) & MASK_6BITS];
buffer[pos++] = encodeTable[(bitWorkArea << 2) & MASK_6BITS];
@@ -382,7 +372,7 @@ void encode(byte[] in, int inPos, int inAvail) {
} else {
for (int i = 0; i < inAvail; i++) {
ensureBufferSize(encodeSize);
- modulus = (modulus+1) % BYTES_PER_UNENCODED_BLOCK;
+ modulus = (modulus + 1) % BYTES_PER_UNENCODED_BLOCK;
int b = in[inPos++];
if (b < 0) {
b += 256;
@@ -420,12 +410,9 @@ void encode(byte[] in, int inPos, int inAvail) {
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*
*
- * @param in
- * byte[] array of ascii data to base64 decode.
- * @param inPos
- * Position to start reading data from.
- * @param inAvail
- * Amount of bytes available from input for encoding.
+ * @param in byte[] array of ascii data to base64 decode.
+ * @param inPos Position to start reading data from.
+ * @param inAvail Amount of bytes available from input for encoding.
*/
void decode(byte[] in, int inPos, int inAvail) {
if (eof) {
@@ -445,7 +432,7 @@ void decode(byte[] in, int inPos, int inAvail) {
if (b >= 0 && b < DECODE_TABLE.length) {
int result = DECODE_TABLE[b];
if (result >= 0) {
- modulus = (modulus+1) % BYTES_PER_ENCODED_BLOCK;
+ modulus = (modulus + 1) % BYTES_PER_ENCODED_BLOCK;
bitWorkArea = (bitWorkArea << BITS_PER_ENCODED_BYTE) + result;
if (modulus == 0) {
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
@@ -468,11 +455,11 @@ void decode(byte[] in, int inPos, int inAvail) {
switch (modulus) {
// case 1: // 6 bits - ignore entirely
// break;
- case 2 : // 12 bits = 8 + 4
+ case 2: // 12 bits = 8 + 4
bitWorkArea = bitWorkArea >> 4; // dump the extra 4 bits
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
break;
- case 3 : // 18 bits = 8 + 8 + 2
+ case 3: // 18 bits = 8 + 8 + 2
bitWorkArea = bitWorkArea >> 2; // dump 2 bits
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
@@ -484,8 +471,7 @@ void decode(byte[] in, int inPos, int inAvail) {
/**
* Returns whether or not the octet is in the base 64 alphabet.
*
- * @param octet
- * The value to test
+ * @param octet The value to test
* @return true if the value is defined in the the base 64 alphabet, false otherwise.
* @since 1.4
*/
@@ -497,11 +483,10 @@ public static boolean isBase64(byte octet) {
* Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the
* method treats whitespace as valid.
*
- * @param base64
- * String to test
+ * @param base64 String to test
* @return true if all characters in the String are valid characters in the Base64 alphabet or if
- * the String is empty; false, otherwise
- * @since 1.5
+ * the String is empty; false, otherwise
+ * @since 1.5
*/
public static boolean isBase64(String base64) {
return isBase64(StringUtils.getBytesUtf8(base64));
@@ -511,10 +496,9 @@ public static boolean isBase64(String base64) {
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
* method treats whitespace as valid.
*
- * @param arrayOctet
- * byte array to test
+ * @param arrayOctet byte array to test
* @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
- * false, otherwise
+ * false, otherwise
* @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
*/
public static boolean isArrayByteBase64(byte[] arrayOctet) {
@@ -525,10 +509,9 @@ public static boolean isArrayByteBase64(byte[] arrayOctet) {
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
* method treats whitespace as valid.
*
- * @param arrayOctet
- * byte array to test
+ * @param arrayOctet byte array to test
* @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
- * false, otherwise
+ * false, otherwise
* @since 1.5
*/
public static boolean isBase64(byte[] arrayOctet) {
@@ -543,8 +526,7 @@ public static boolean isBase64(byte[] arrayOctet) {
/**
* Encodes binary data using the base64 algorithm but does not chunk the output.
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return byte[] containing Base64 characters in their UTF-8 representation.
*/
public static byte[] encodeBase64(byte[] binaryData) {
@@ -553,12 +535,11 @@ public static byte[] encodeBase64(byte[] binaryData) {
/**
* Encodes binary data using the base64 algorithm but does not chunk the output.
- *
+ *
* NOTE: We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to
* single-line non-chunking (commons-codec-1.5).
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return String containing Base64 characters.
* @since 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not).
*/
@@ -570,8 +551,7 @@ public static String encodeBase64String(byte[] binaryData) {
* Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
* url-safe variation emits - and _ instead of + and / characters.
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return byte[] containing Base64 characters in their UTF-8 representation.
* @since 1.4
*/
@@ -583,8 +563,7 @@ public static byte[] encodeBase64URLSafe(byte[] binaryData) {
* Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
* url-safe variation emits - and _ instead of + and / characters.
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return String containing Base64 characters
* @since 1.4
*/
@@ -595,8 +574,7 @@ public static String encodeBase64URLSafeString(byte[] binaryData) {
/**
* Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return Base64 characters chunked in 76 character blocks
*/
public static byte[] encodeBase64Chunked(byte[] binaryData) {
@@ -606,13 +584,10 @@ public static byte[] encodeBase64Chunked(byte[] binaryData) {
/**
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
*
- * @param binaryData
- * Array containing binary data to encode.
- * @param isChunked
- * if true this encoder will chunk the base64 output into 76 character blocks
+ * @param binaryData Array containing binary data to encode.
+ * @param isChunked if true this encoder will chunk the base64 output into 76 character blocks
* @return Base64-encoded data.
- * @throws IllegalArgumentException
- * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
+ * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
return encodeBase64(binaryData, isChunked, false);
@@ -621,15 +596,11 @@ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
/**
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
*
- * @param binaryData
- * Array containing binary data to encode.
- * @param isChunked
- * if true this encoder will chunk the base64 output into 76 character blocks
- * @param urlSafe
- * if true this encoder will emit - and _ instead of the usual + and / characters.
+ * @param binaryData Array containing binary data to encode.
+ * @param isChunked if true this encoder will chunk the base64 output into 76 character blocks
+ * @param urlSafe if true this encoder will emit - and _ instead of the usual + and / characters.
* @return Base64-encoded data.
- * @throws IllegalArgumentException
- * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
+ * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
* @since 1.4
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe) {
@@ -639,17 +610,12 @@ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean
/**
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
*
- * @param binaryData
- * Array containing binary data to encode.
- * @param isChunked
- * if true this encoder will chunk the base64 output into 76 character blocks
- * @param urlSafe
- * if true this encoder will emit - and _ instead of the usual + and / characters.
- * @param maxResultSize
- * The maximum result size to accept.
+ * @param binaryData Array containing binary data to encode.
+ * @param isChunked if true this encoder will chunk the base64 output into 76 character blocks
+ * @param urlSafe if true this encoder will emit - and _ instead of the usual + and / characters.
+ * @param maxResultSize The maximum result size to accept.
* @return Base64-encoded data.
- * @throws IllegalArgumentException
- * Thrown when the input array needs an output array bigger than maxResultSize
+ * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than maxResultSize
* @since 1.4
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
@@ -674,8 +640,7 @@ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean
/**
* Decodes a Base64 String into octets
*
- * @param base64String
- * String containing Base64 data
+ * @param base64String String containing Base64 data
* @return Array containing decoded data.
* @since 1.4
*/
@@ -686,8 +651,7 @@ public static byte[] decodeBase64(String base64String) {
/**
* Decodes Base64 data into octets
*
- * @param base64Data
- * Byte array containing Base64 data
+ * @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decodeBase64(byte[] base64Data) {
@@ -697,11 +661,11 @@ public static byte[] decodeBase64(byte[] base64Data) {
// Implementation of the Encoder Interface
// Implementation of integer encoding used for crypto
+
/**
* Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
*
- * @param pArray
- * a byte array containing base64 character data
+ * @param pArray a byte array containing base64 character data
* @return A BigInteger
* @since 1.4
*/
@@ -712,11 +676,9 @@ public static BigInteger decodeInteger(byte[] pArray) {
/**
* Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
*
- * @param bigInt
- * a BigInteger
+ * @param bigInt a BigInteger
* @return A byte array containing base64 character data
- * @throws NullPointerException
- * if null is passed in
+ * @throws NullPointerException if null is passed in
* @since 1.4
*/
public static byte[] encodeInteger(BigInteger bigInt) {
@@ -729,8 +691,7 @@ public static byte[] encodeInteger(BigInteger bigInt) {
/**
* Returns a byte-array representation of a BigInteger without sign bit.
*
- * @param bigInt
- * BigInteger to be converted
+ * @param bigInt BigInteger to be converted
* @return a byte array representation of the BigInteger parameter
*/
static byte[] toIntegerBytes(BigInteger bigInt) {
@@ -760,8 +721,7 @@ static byte[] toIntegerBytes(BigInteger bigInt) {
/**
* Returns whether or not the octet is in the Base32 alphabet.
*
- * @param octet
- * The value to test
+ * @param octet The value to test
* @return true if the value is defined in the the Base32 alphabet false otherwise.
*/
protected boolean isInAlphabet(byte octet) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/BaseNCodec.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/BaseNCodec.java
index 632bc8ec..9151055f 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/BaseNCodec.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/BaseNCodec.java
@@ -44,7 +44,7 @@
public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
/**
- * MIME chunk size per RFC 2045 section 6.8.
+ * MIME chunk size per RFC 2045 section 6.8.
*
*
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
@@ -75,7 +75,9 @@ public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
*/
private static final int DEFAULT_BUFFER_SIZE = 8192;
- /** Mask used to extract 8 bits, used in decoding bytes */
+ /**
+ * Mask used to extract 8 bits, used in decoding bytes
+ */
protected static final int MASK_8BITS = 0xff;
/**
@@ -85,10 +87,14 @@ public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later
- /** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
+ /**
+ * Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32
+ */
private final int unencodedBlockSize;
- /** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
+ /**
+ * Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32
+ */
private final int encodedBlockSize;
/**
@@ -139,15 +145,16 @@ public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
/**
* Note lineLength is rounded down to the nearest multiple of {@link #encodedBlockSize}
* If chunkSeparatorLength is zero, then chunking is disabled.
- * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
- * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
- * @param lineLength if > 0, use chunking with a length lineLength
+ *
+ * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
+ * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
+ * @param lineLength if > 0, use chunking with a length lineLength
* @param chunkSeparatorLength the chunk separator length, if relevant
*/
- protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength){
+ protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength) {
this.unencodedBlockSize = unencodedBlockSize;
this.encodedBlockSize = encodedBlockSize;
- this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
+ this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
this.chunkSeparatorLength = chunkSeparatorLength;
}
@@ -178,7 +185,9 @@ protected int getDefaultBufferSize() {
return DEFAULT_BUFFER_SIZE;
}
- /** Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}. */
+ /**
+ * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
+ */
private void resizeBuffer() {
if (buffer == null) {
buffer = new byte[getDefaultBufferSize()];
@@ -196,8 +205,8 @@ private void resizeBuffer() {
*
* @param size minimum spare space required
*/
- protected void ensureBufferSize(int size){
- if ((buffer == null) || (buffer.length < pos + size)){
+ protected void ensureBufferSize(int size) {
+ if ((buffer == null) || (buffer.length < pos + size)) {
resizeBuffer();
}
}
@@ -206,12 +215,9 @@ protected void ensureBufferSize(int size){
* Extracts buffered data into the provided byte[] array, starting at position bPos,
* up to a maximum of bAvail bytes. Returns how many bytes were actually extracted.
*
- * @param b
- * byte[] array to extract the buffered data into.
- * @param bPos
- * position in byte[] array to start extraction at.
- * @param bAvail
- * amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
+ * @param b byte[] array to extract the buffered data into.
+ * @param bPos position in byte[] array to start extraction at.
+ * @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
* @return The number of bytes successfully extracted into the provided byte[] array.
*/
int readResults(byte[] b, int bPos, int bAvail) { // package protected for access from I/O streams
@@ -230,18 +236,18 @@ int readResults(byte[] b, int bPos, int bAvail) { // package protected for acce
/**
* Checks if a byte value is whitespace or not.
* Whitespace is taken to mean: space, tab, CR, LF
- * @param byteToCheck
- * the byte to check
+ *
+ * @param byteToCheck the byte to check
* @return true if byte is whitespace, false otherwise
*/
protected static boolean isWhiteSpace(byte byteToCheck) {
switch (byteToCheck) {
- case ' ' :
- case '\n' :
- case '\r' :
- case '\t' :
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
return true;
- default :
+ default:
return false;
}
}
@@ -262,11 +268,9 @@ private void reset() {
* Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the
* Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].
*
- * @param pObject
- * Object to encode
+ * @param pObject Object to encode
* @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
- * @throws EncoderException
- * if the parameter supplied is not of type byte[]
+ * @throws EncoderException if the parameter supplied is not of type byte[]
*/
public Object encode(Object pObject) throws EncoderException {
if (!(pObject instanceof byte[])) {
@@ -278,8 +282,7 @@ public Object encode(Object pObject) throws EncoderException {
/**
* Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.
*
- * @param pArray
- * a byte array containing binary data
+ * @param pArray a byte array containing binary data
* @return A String containing only Base-N character data
*/
public String encodeToString(byte[] pArray) {
@@ -290,11 +293,9 @@ public String encodeToString(byte[] pArray) {
* Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the
* Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.
*
- * @param pObject
- * Object to decode
+ * @param pObject Object to decode
* @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied.
- * @throws DecoderException
- * if the parameter supplied is not of type byte[]
+ * @throws DecoderException if the parameter supplied is not of type byte[]
*/
public Object decode(Object pObject) throws DecoderException {
if (pObject instanceof byte[]) {
@@ -309,8 +310,7 @@ public Object decode(Object pObject) throws DecoderException {
/**
* Decodes a String containing characters in the Base-N alphabet.
*
- * @param pArray
- * A String containing Base-N character data
+ * @param pArray A String containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(String pArray) {
@@ -320,8 +320,7 @@ public byte[] decode(String pArray) {
/**
* Decodes a byte[] containing characters in the Base-N alphabet.
*
- * @param pArray
- * A byte array containing Base-N character data
+ * @param pArray A byte array containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(byte[] pArray) {
@@ -339,8 +338,7 @@ public byte[] decode(byte[] pArray) {
/**
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
*
- * @param pArray
- * a byte array containing binary data
+ * @param pArray a byte array containing binary data
* @return A byte array containing only the basen alphabetic character data
*/
public byte[] encode(byte[] pArray) {
@@ -362,7 +360,7 @@ public byte[] encode(byte[] pArray) {
* @param pArray a byte array containing binary data
* @return String containing only character data in the appropriate alphabet.
*/
- public String encodeAsString(byte[] pArray){
+ public String encodeAsString(byte[] pArray) {
return StringUtils.newStringUtf8(encode(pArray));
}
@@ -375,7 +373,6 @@ public String encodeAsString(byte[] pArray){
* Does not allow whitespace or pad.
*
* @param value The value to test
- *
* @return true if the value is defined in the current alphabet, false otherwise.
*/
protected abstract boolean isInAlphabet(byte value);
@@ -386,9 +383,8 @@ public String encodeAsString(byte[] pArray){
*
* @param arrayOctet byte array to test
* @param allowWSPad if true, then whitespace and PAD are also allowed
- *
* @return true if all bytes are valid characters in the alphabet or if the byte array is empty;
- * false, otherwise
+ * false, otherwise
*/
public boolean isInAlphabet(byte[] arrayOctet, boolean allowWSPad) {
for (int i = 0; i < arrayOctet.length; i++) {
@@ -406,7 +402,7 @@ public boolean isInAlphabet(byte[] arrayOctet, boolean allowWSPad) {
*
* @param basen String to test
* @return true if all characters in the String are valid characters in the alphabet or if
- * the String is empty; false, otherwise
+ * the String is empty; false, otherwise
* @see #isInAlphabet(byte[], boolean)
*/
public boolean isInAlphabet(String basen) {
@@ -415,11 +411,10 @@ public boolean isInAlphabet(String basen) {
/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
- *
+ *
* Intended for use in checking line-ending arrays
*
- * @param arrayOctet
- * byte array to test
+ * @param arrayOctet byte array to test
* @return true if any byte is a valid character in the alphabet or PAD; false otherwise
*/
protected boolean containsAlphabetOrPad(byte[] arrayOctet) {
@@ -438,17 +433,16 @@ protected boolean containsAlphabetOrPad(byte[] arrayOctet) {
* Calculates the amount of space needed to encode the supplied array.
*
* @param pArray byte[] array which will later be encoded
- *
* @return amount of space needed to encoded the supplied array.
* Returns a long since a max-len array will require > Integer.MAX_VALUE
*/
public long getEncodedLength(byte[] pArray) {
// Calculate non-chunked size - rounded up to allow for padding
// cast to long is needed to avoid possibility of overflow
- long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
+ long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long) encodedBlockSize;
if (lineLength > 0) { // We're using chunking
// Round up to nearest multiple
- len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
+ len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength;
}
return len;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryCodec.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryCodec.java
index 5472e43c..5a0afc83 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryCodec.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryCodec.java
@@ -36,47 +36,67 @@
/**
* Converts between byte arrays and strings of "0"s and "1"s.
- *
+ *
* TODO: may want to add more bit vector functions like and/or/xor/nand
* TODO: also might be good to generate boolean[] from byte[] et cetera.
*
* @author Apache Software Foundation
- * @since 1.3
* @version $Id$
+ * @since 1.3
*/
public class BinaryCodec implements BinaryDecoder, BinaryEncoder {
/*
* tried to avoid using ArrayUtils to minimize dependencies while using these empty arrays - dep is just not worth
* it.
*/
- /** Empty char array. */
+ /**
+ * Empty char array.
+ */
private static final char[] EMPTY_CHAR_ARRAY = new char[0];
- /** Empty byte array. */
+ /**
+ * Empty byte array.
+ */
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
- /** Mask for bit 0 of a byte. */
+ /**
+ * Mask for bit 0 of a byte.
+ */
private static final int BIT_0 = 1;
- /** Mask for bit 1 of a byte. */
+ /**
+ * Mask for bit 1 of a byte.
+ */
private static final int BIT_1 = 0x02;
- /** Mask for bit 2 of a byte. */
+ /**
+ * Mask for bit 2 of a byte.
+ */
private static final int BIT_2 = 0x04;
- /** Mask for bit 3 of a byte. */
+ /**
+ * Mask for bit 3 of a byte.
+ */
private static final int BIT_3 = 0x08;
- /** Mask for bit 4 of a byte. */
+ /**
+ * Mask for bit 4 of a byte.
+ */
private static final int BIT_4 = 0x10;
- /** Mask for bit 5 of a byte. */
+ /**
+ * Mask for bit 5 of a byte.
+ */
private static final int BIT_5 = 0x20;
- /** Mask for bit 6 of a byte. */
+ /**
+ * Mask for bit 6 of a byte.
+ */
private static final int BIT_6 = 0x40;
- /** Mask for bit 7 of a byte. */
+ /**
+ * Mask for bit 7 of a byte.
+ */
private static final int BIT_7 = 0x80;
private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7};
@@ -84,8 +104,7 @@ public class BinaryCodec implements BinaryDecoder, BinaryEncoder {
/**
* Converts an array of raw binary data into an array of ASCII 0 and 1 characters.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return 0 and 1 ASCII character bytes one for each bit of the argument
*/
public byte[] encode(byte[] raw) {
@@ -95,11 +114,9 @@ public byte[] encode(byte[] raw) {
/**
* Converts an array of raw binary data into an array of ASCII 0 and 1 chars.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return 0 and 1 ASCII character chars one for each bit of the argument
- * @throws EncoderException
- * if the argument is not a byte[]
+ * @throws EncoderException if the argument is not a byte[]
*/
public Object encode(Object raw) throws EncoderException {
if (!(raw instanceof byte[])) {
@@ -111,11 +128,9 @@ public Object encode(Object raw) throws EncoderException {
/**
* Decodes a byte array where each byte represents an ASCII '0' or '1'.
*
- * @param ascii
- * each byte represents an ASCII '0' or '1'
+ * @param ascii each byte represents an ASCII '0' or '1'
* @return the raw encoded binary where each bit corresponds to a byte in the byte array argument
- * @throws DecoderException
- * if argument is not a byte[], char[] or String
+ * @throws DecoderException if argument is not a byte[], char[] or String
*/
public Object decode(Object ascii) throws DecoderException {
if (ascii == null) {
@@ -136,8 +151,7 @@ public Object decode(Object ascii) throws DecoderException {
/**
* Decodes a byte array where each byte represents an ASCII '0' or '1'.
*
- * @param ascii
- * each byte represents an ASCII '0' or '1'
+ * @param ascii each byte represents an ASCII '0' or '1'
* @return the raw encoded binary where each bit corresponds to a byte in the byte array argument
*/
public byte[] decode(byte[] ascii) {
@@ -147,8 +161,7 @@ public byte[] decode(byte[] ascii) {
/**
* Decodes a String where each char of the String represents an ASCII '0' or '1'.
*
- * @param ascii
- * String of '0' and '1' characters
+ * @param ascii String of '0' and '1' characters
* @return the raw encoded binary where each bit corresponds to a byte in the byte array argument
*/
public byte[] toByteArray(String ascii) {
@@ -163,11 +176,11 @@ public byte[] toByteArray(String ascii) {
// static codec operations
//
// ------------------------------------------------------------------------
+
/**
* Decodes a char array where each char represents an ASCII '0' or '1'.
*
- * @param ascii
- * each char represents an ASCII '0' or '1'
+ * @param ascii each char represents an ASCII '0' or '1'
* @return the raw encoded binary where each bit corresponds to a char in the char array argument
*/
public static byte[] fromAscii(char[] ascii) {
@@ -193,8 +206,7 @@ public static byte[] fromAscii(char[] ascii) {
/**
* Decodes a byte array where each byte represents an ASCII '0' or '1'.
*
- * @param ascii
- * each byte represents an ASCII '0' or '1'
+ * @param ascii each byte represents an ASCII '0' or '1'
* @return the raw encoded binary where each bit corresponds to a byte in the byte array argument
*/
public static byte[] fromAscii(byte[] ascii) {
@@ -220,8 +232,7 @@ public static byte[] fromAscii(byte[] ascii) {
/**
* Returns true if the given array is null or empty (size 0.)
*
- * @param array
- * the source array
+ * @param array the source array
* @return true if the given array is null or empty (size 0.)
*/
private static boolean isEmpty(byte[] array) {
@@ -232,8 +243,7 @@ private static boolean isEmpty(byte[] array) {
* Converts an array of raw binary data into an array of ASCII 0 and 1 character bytes - each byte is a truncated
* char.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return an array of 0 and 1 character bytes for each bit of the argument
*/
public static byte[] toAsciiBytes(byte[] raw) {
@@ -261,8 +271,7 @@ public static byte[] toAsciiBytes(byte[] raw) {
/**
* Converts an array of raw binary data into an array of ASCII 0 and 1 characters.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return an array of 0 and 1 characters for each bit of the argument
*/
public static char[] toAsciiChars(byte[] raw) {
@@ -290,8 +299,7 @@ public static char[] toAsciiChars(byte[] raw) {
/**
* Converts an array of raw binary data into a String of ASCII 0 and 1 characters.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return a String of 0 and 1 characters representing the binary data
*/
public static String toAsciiString(byte[] raw) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryDecoder.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryDecoder.java
index 1291e457..89cf14cd 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryDecoder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryDecoder.java
@@ -46,13 +46,11 @@ public interface BinaryDecoder extends Decoder {
* Decodes a byte array and returns the results as a byte array.
*
* @param source A byte array which has been encoded with the
- * appropriate encoder
- *
+ * appropriate encoder
* @return a byte array that contains decoded content
- *
* @throws DecoderException A decoder exception is thrown
- * if a Decoder encounters a failure condition during
- * the decode process.
+ * if a Decoder encounters a failure condition during
+ * the decode process.
*/
byte[] decode(byte[] source) throws DecoderException;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryEncoder.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryEncoder.java
index d5363df4..b4cb04ce 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryEncoder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryEncoder.java
@@ -46,12 +46,10 @@ public interface BinaryEncoder extends Encoder {
* as a byte array.
*
* @param source Data to be encoded
- *
* @return A byte array containing the encoded data
- *
* @throws EncoderException thrown if the Encoder
- * encounters a failure condition during the
- * encoding process.
+ * encounters a failure condition during the
+ * encoding process.
*/
byte[] encode(byte[] source) throws EncoderException;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/CharEncoding.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/CharEncoding.java
index 97324597..297c4e3e 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/CharEncoding.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/CharEncoding.java
@@ -35,7 +35,7 @@
/**
* Character encoding names required of every implementation of the Java platform.
- *
+ *
* From the Java documentation Standard * charsets: *
@@ -59,14 +59,14 @@ * Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order * accepted on input, big-endian used on output.) * - * + *
* This perhaps would best belong in the [lang] project. Even if a similar interface is defined in [lang], it is not * forseen that [codec] would be made to depend on [lang]. * - * @see Standard charsets * @author Apache Software Foundation - * @since 1.4 * @version $Id$ + * @see Standard charsets + * @since 1.4 */ public class CharEncoding { /** @@ -139,4 +139,4 @@ public class CharEncoding { * @see Standard charsets */ public static final String UTF_8 = "UTF-8"; -} \ No newline at end of file +} diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Decoder.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Decoder.java index d90a8f6c..cd2aab62 100644 --- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Decoder.java +++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Decoder.java @@ -58,14 +58,12 @@ public interface Decoder { * this decode method will throw a DecoderException. * * @param source the object to decode - * * @return a 'decoded" object - * * @throws DecoderException a decoder exception can - * be thrown for any number of reasons. Some good - * candidates are that the parameter passed to this - * method is null, a param cannot be cast to the - * appropriate type for a specific encoder. + * be thrown for any number of reasons. Some good + * candidates are that the parameter passed to this + * method is null, a param cannot be cast to the + * appropriate type for a specific encoder. */ Object decode(Object source) throws DecoderException; } diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/DecoderException.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/DecoderException.java index dd8ebe5e..6475647f 100644 --- a/kin-sdk/kin-base/src/main/java/kin/base/codec/DecoderException.java +++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/DecoderException.java @@ -63,8 +63,7 @@ public DecoderException() { * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently * be initialized by a call to {@link #initCause}. * - * @param message - * The detail message which is saved for later retrieval by the {@link #getMessage()} method. + * @param message The detail message which is saved for later retrieval by the {@link #getMessage()} method. */ public DecoderException(String message) { super(message); @@ -78,11 +77,9 @@ public DecoderException(String message) { * exception's detail message. *
* - * @param message - * The detail message which is saved for later retrieval by the {@link #getMessage()} method. - * @param cause - * The cause which is saved for later retrieval by the {@link #getCause()} method. Anull
- * value is permitted, and indicates that the cause is nonexistent or unknown.
+ * @param message The detail message which is saved for later retrieval by the {@link #getMessage()} method.
+ * @param cause The cause which is saved for later retrieval by the {@link #getCause()} method. A null
+ * value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public DecoderException(String message, Throwable cause) {
@@ -94,9 +91,8 @@ public DecoderException(String message, Throwable cause) {
* null : cause.toString()) (which typically contains the class and detail message of cause).
* This constructor is useful for exceptions that are little more than wrappers for other throwables.
*
- * @param cause
- * The cause which is saved for later retrieval by the {@link #getCause()} method. A null
- * value is permitted, and indicates that the cause is nonexistent or unknown.
+ * @param cause The cause which is saved for later retrieval by the {@link #getCause()} method. A null
+ * value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public DecoderException(Throwable cause) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Encoder.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Encoder.java
index bb6208dc..17626e2b 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Encoder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Encoder.java
@@ -50,12 +50,10 @@ public interface Encoder {
* or Strings depending on the implementation used.
*
* @param source An object ot encode
- *
* @return An "encoded" Object
- *
* @throws EncoderException an encoder exception is
- * thrown if the encoder experiences a failure
- * condition during the encoding process.
+ * thrown if the encoder experiences a failure
+ * condition during the encoding process.
*/
Object encode(Object source) throws EncoderException;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/EncoderException.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/EncoderException.java
index 5c831c23..839aee36 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/EncoderException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/EncoderException.java
@@ -64,8 +64,7 @@ public EncoderException() {
* Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
* be initialized by a call to {@link #initCause}.
*
- * @param message
- * a useful message relating to the encoder specific error.
+ * @param message a useful message relating to the encoder specific error.
*/
public EncoderException(String message) {
super(message);
@@ -79,11 +78,9 @@ public EncoderException(String message) {
* exception's detail message.
*
*
- * @param message
- * The detail message which is saved for later retrieval by the {@link #getMessage()} method.
- * @param cause
- * The cause which is saved for later retrieval by the {@link #getCause()} method. A null
- * value is permitted, and indicates that the cause is nonexistent or unknown.
+ * @param message The detail message which is saved for later retrieval by the {@link #getMessage()} method.
+ * @param cause The cause which is saved for later retrieval by the {@link #getCause()} method. A null
+ * value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public EncoderException(String message, Throwable cause) {
@@ -95,9 +92,8 @@ public EncoderException(String message, Throwable cause) {
* null : cause.toString()) (which typically contains the class and detail message of cause).
* This constructor is useful for exceptions that are little more than wrappers for other throwables.
*
- * @param cause
- * The cause which is saved for later retrieval by the {@link #getCause()} method. A null
- * value is permitted, and indicates that the cause is nonexistent or unknown.
+ * @param cause The cause which is saved for later retrieval by the {@link #getCause()} method. A null
+ * value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public EncoderException(Throwable cause) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Hex.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Hex.java
index b241d389..33dcaaf9 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Hex.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Hex.java
@@ -39,9 +39,9 @@
* Converts hexadecimal Strings. The charset used for certain operation can be set, the default is set in
* {@link #DEFAULT_CHARSET_NAME}
*
- * @since 1.1
* @author Apache Software Foundation
* @version $Id$
+ * @since 1.1
*/
public class Hex implements BinaryEncoder, BinaryDecoder {
@@ -67,11 +67,9 @@ public class Hex implements BinaryEncoder, BinaryDecoder {
* returned array will be half the length of the passed array, as it takes two characters to represent any given
* byte. An exception is thrown if the passed char array has an odd number of elements.
*
- * @param data
- * An array of characters containing hexadecimal digits
+ * @param data An array of characters containing hexadecimal digits
* @return A byte array containing binary data decoded from the supplied char array.
- * @throws DecoderException
- * Thrown if an odd number or illegal of characters is supplied
+ * @throws DecoderException Thrown if an odd number or illegal of characters is supplied
*/
public static byte[] decodeHex(char[] data) throws DecoderException {
@@ -100,8 +98,7 @@ public static byte[] decodeHex(char[] data) throws DecoderException {
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
- * @param data
- * a byte[] to convert to Hex characters
+ * @param data a byte[] to convert to Hex characters
* @return A char[] containing hexadecimal characters
*/
public static char[] encodeHex(byte[] data) {
@@ -113,10 +110,8 @@ public static char[] encodeHex(byte[] data) {
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
- * @param data
- * a byte[] to convert to Hex characters
- * @param toLowerCase
- * true converts to lowercase, false to uppercase
+ * @param data a byte[] to convert to Hex characters
+ * @param toLowerCase true converts to lowercase, false to uppercase
* @return A char[] containing hexadecimal characters
* @since 1.4
*/
@@ -129,10 +124,8 @@ public static char[] encodeHex(byte[] data, boolean toLowerCase) {
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
- * @param data
- * a byte[] to convert to Hex characters
- * @param toDigits
- * the output alphabet
+ * @param data a byte[] to convert to Hex characters
+ * @param toDigits the output alphabet
* @return A char[] containing hexadecimal characters
* @since 1.4
*/
@@ -151,8 +144,7 @@ protected static char[] encodeHex(byte[] data, char[] toDigits) {
* Converts an array of bytes into a String representing the hexadecimal values of each byte in order. The returned
* String will be double the length of the passed array, as it takes two characters to represent any given byte.
*
- * @param data
- * a byte[] to convert to Hex characters
+ * @param data a byte[] to convert to Hex characters
* @return A String containing hexadecimal characters
* @since 1.4
*/
@@ -163,13 +155,10 @@ public static String encodeHexString(byte[] data) {
/**
* Converts a hexadecimal character to an integer.
*
- * @param ch
- * A character to convert to an integer digit
- * @param index
- * The index of the character in the source
+ * @param ch A character to convert to an integer digit
+ * @param index The index of the character in the source
* @return An integer
- * @throws DecoderException
- * Thrown if ch is an illegal hex character
+ * @throws DecoderException Thrown if ch is an illegal hex character
*/
protected static int toDigit(char ch, int index) throws DecoderException {
int digit = Character.digit(ch, 16);
@@ -192,8 +181,7 @@ public Hex() {
/**
* Creates a new codec with the given charset name.
*
- * @param csName
- * the charset name.
+ * @param csName the charset name.
* @since 1.4
*/
public Hex(String csName) {
@@ -205,11 +193,9 @@ public Hex(String csName) {
* The returned array will be half the length of the passed array, as it takes two characters to represent any given
* byte. An exception is thrown if the passed char array has an odd number of elements.
*
- * @param array
- * An array of character bytes containing hexadecimal digits
+ * @param array An array of character bytes containing hexadecimal digits
* @return A byte array containing binary data decoded from the supplied byte array (representing characters).
- * @throws DecoderException
- * Thrown if an odd number of characters is supplied to this function
+ * @throws DecoderException Thrown if an odd number of characters is supplied to this function
* @see #decodeHex(char[])
*/
public byte[] decode(byte[] array) throws DecoderException {
@@ -225,12 +211,10 @@ public byte[] decode(byte[] array) throws DecoderException {
* same values. The returned array will be half the length of the passed String or array, as it takes two characters
* to represent any given byte. An exception is thrown if the passed char array has an odd number of elements.
*
- * @param object
- * A String or, an array of character bytes containing hexadecimal digits
+ * @param object A String or, an array of character bytes containing hexadecimal digits
* @return A byte array containing binary data decoded from the supplied byte array (representing characters).
- * @throws DecoderException
- * Thrown if an odd number of characters is supplied to this function or the object is not a String or
- * char[]
+ * @throws DecoderException Thrown if an odd number of characters is supplied to this function or the object is not a String or
+ * char[]
* @see #decodeHex(char[])
*/
public Object decode(Object object) throws DecoderException {
@@ -251,12 +235,10 @@ public Object decode(Object object) throws DecoderException {
* {@link #getCharsetName()}.
*
*
- * @param array
- * a byte[] to convert to Hex characters
+ * @param array a byte[] to convert to Hex characters
* @return A byte[] containing the bytes of the hexadecimal characters
- * @throws IllegalStateException
- * if the charsetName is invalid. This API throws {@link IllegalStateException} instead of
- * {@link UnsupportedEncodingException} for backward compatibility.
+ * @throws IllegalStateException if the charsetName is invalid. This API throws {@link IllegalStateException} instead of
+ * {@link UnsupportedEncodingException} for backward compatibility.
* @see #encodeHex(byte[])
*/
public byte[] encode(byte[] array) {
@@ -272,11 +254,9 @@ public byte[] encode(byte[] array) {
* {@link #getCharsetName()}.
*
*
- * @param object
- * a String, or byte[] to convert to Hex characters
+ * @param object a String, or byte[] to convert to Hex characters
* @return A char[] containing hexadecimal characters
- * @throws EncoderException
- * Thrown if the given object is not a String or byte[]
+ * @throws EncoderException Thrown if the given object is not a String or byte[]
* @see #encodeHex(byte[])
*/
public Object encode(Object object) throws EncoderException {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/StringUtils.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/StringUtils.java
index 1c7781bf..dd7f55c3 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/StringUtils.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/StringUtils.java
@@ -40,10 +40,10 @@
* Converts String to and from bytes using the encodings required by the Java specification. These encodings are specified in Standard charsets
*
- * @see CharEncoding
- * @see Standard charsets
* @author Gary Gregory
* @version $Id$
+ * @see CharEncoding
+ * @see Standard charsets
* @since 1.4
*/
public class StringUtils {
@@ -52,11 +52,9 @@ public class StringUtils {
* Encodes the given string into a sequence of bytes using the ISO-8859-1 charset, storing the result into a new
* byte array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -68,11 +66,9 @@ public static byte[] getBytesIso8859_1(String string) {
* Encodes the given string into a sequence of bytes using the US-ASCII charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -84,11 +80,9 @@ public static byte[] getBytesUsAscii(String string) {
* Encodes the given string into a sequence of bytes using the UTF-16 charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -100,11 +94,9 @@ public static byte[] getBytesUtf16(String string) {
* Encodes the given string into a sequence of bytes using the UTF-16BE charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -116,11 +108,9 @@ public static byte[] getBytesUtf16Be(String string) {
* Encodes the given string into a sequence of bytes using the UTF-16LE charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -132,11 +122,9 @@ public static byte[] getBytesUtf16Le(String string) {
* Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -152,14 +140,11 @@ public static byte[] getBytesUtf8(String string) {
* should never happen for a required charset name. Use this method when the encoding is required to be in the JRE.
*
*
- * @param string
- * the String to encode, may be null
- * @param charsetName
- * The name of a required {@link java.nio.charset.Charset}
+ * @param string the String to encode, may be null
+ * @param charsetName The name of a required {@link java.nio.charset.Charset}
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
- * required charset name.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
+ * required charset name.
* @see CharEncoding
* @see String#getBytes(String)
*/
@@ -185,15 +170,12 @@ private static IllegalStateException newIllegalStateException(String charsetName
* should never happen for a required charset name. Use this method when the encoding is required to be in the JRE.
*
*
- * @param bytes
- * The bytes to be decoded into characters, may be null
- * @param charsetName
- * The name of a required {@link java.nio.charset.Charset}
+ * @param bytes The bytes to be decoded into characters, may be null
+ * @param charsetName The name of a required {@link java.nio.charset.Charset}
* @return A new String decoded from the specified array of bytes using the given charset,
- * or null if the input byte arrray was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
- * required charset name.
+ * or null if the input byte arrray was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
+ * required charset name.
* @see CharEncoding
* @see String#String(byte[], String)
*/
@@ -211,13 +193,11 @@ public static String newString(byte[] bytes, String charsetName) {
/**
* Constructs a new String by decoding the specified array of bytes using the ISO-8859-1 charset.
*
- * @param bytes
- * The bytes to be decoded into characters, may be null
+ * @param bytes The bytes to be decoded into characters, may be null
* @return A new String decoded from the specified array of bytes using the ISO-8859-1 charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringIso8859_1(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.ISO_8859_1);
@@ -226,13 +206,11 @@ public static String newStringIso8859_1(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the US-ASCII charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the US-ASCII charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUsAscii(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.US_ASCII);
@@ -241,13 +219,11 @@ public static String newStringUsAscii(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the UTF-16 charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the UTF-16 charset
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUtf16(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.UTF_16);
@@ -256,13 +232,11 @@ public static String newStringUtf16(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the UTF-16BE charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the UTF-16BE charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUtf16Be(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.UTF_16BE);
@@ -271,13 +245,11 @@ public static String newStringUtf16Be(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the UTF-16LE charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the UTF-16LE charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUtf16Le(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.UTF_16LE);
@@ -286,13 +258,11 @@ public static String newStringUtf16Le(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the UTF-8 charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the UTF-8 charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUtf8(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.UTF_8);
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/federation/Federation.java b/kin-sdk/kin-base/src/main/java/kin/base/federation/Federation.java
index 78e2bd53..92c97572 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/federation/Federation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/federation/Federation.java
@@ -6,39 +6,40 @@
* @see Federation docs
*/
public class Federation {
- private Federation() {
- }
+ private Federation() {
+ }
- /**
- * This method is a helper method for handling user inputs that contain `destination` value.
- * It accepts two types of values:
- * bob*stellar.org`) it splits Stellar address and then tries to find information about
- * federation server in stellar.toml file for a given domain.GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS) it simply returns the
- * given Account ID.bob*stellar.org`) it splits Stellar address and then tries to find information about
+ * federation server in stellar.toml file for a given domain.GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS) it simply returns the
+ * given Account ID.FederationServer instance.
- *
- * @param serverUri Federation Server URI
- * @param domain Domain name this federation server is responsible for
- * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
- */
- public FederationServer(URI serverUri, String domain) {
- this.serverUri = serverUri;
- if (this.serverUri.getScheme() != "https") {
- throw new FederationServerInvalidException();
+ private final URL serverUri;
+ private final String domain;
+ private static OkHttpClient httpClient = new OkHttpClient();
+
+ /**
+ * Creates a new FederationServer instance.
+ *
+ * @param serverUri Federation Server URI
+ * @param domain Domain name this federation server is responsible for
+ * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
+ */
+ public FederationServer(URL serverUri, String domain) {
+ this.serverUri = serverUri;
+ if (!this.serverUri.getProtocol().equals("https")) {
+ throw new FederationServerInvalidException();
+ }
+ this.domain = domain;
}
- this.domain = domain;
- }
-
- /**
- * Creates a new FederationServer instance.
- *
- * @param serverUri Federation Server URI
- * @param domain Domain name this federation server is responsible for
- * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
- */
- public FederationServer(String serverUri, String domain) {
- try {
- this.serverUri = new URI(serverUri);
- } catch (URISyntaxException e) {
- throw new FederationServerInvalidException();
+
+ /**
+ * Creates a new FederationServer instance.
+ *
+ * @param serverUri Federation Server URI
+ * @param domain Domain name this federation server is responsible for
+ * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
+ */
+ public FederationServer(String serverUri, String domain) {
+ try {
+ this.serverUri = new URL(serverUri);
+ } catch (MalformedURLException e) {
+ throw new FederationServerInvalidException();
+ }
+ this.domain = domain;
}
- this.domain = domain;
- }
-
- /**
- * Creates a FederationServer instance for a given domain.
- * It tries to find a federation server URL in stellar.toml file.
- *
- * @param domain Domain to find a federation server for
- * @return FederationServer
- * @throws ConnectionErrorException Connection problems
- * @throws NoFederationServerException Stellar.toml does not contain federation server info
- * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
- * @throws StellarTomlNotFoundInvalidException Stellar.toml file was not found or was malformed.
- * @see Stellar.toml docs
- */
- public static FederationServer createForDomain(String domain) {
- URI stellarTomlUri;
- try {
- StringBuilder uriBuilder = new StringBuilder();
- uriBuilder.append("https://");
- uriBuilder.append(domain);
- uriBuilder.append("/.well-known/stellar.toml");
- stellarTomlUri = new URI(uriBuilder.toString());
- } catch (URISyntaxException e) {
- throw new RuntimeException(e);
+
+ /**
+ * Creates a FederationServer instance for a given domain.
+ * It tries to find a federation server URL in stellar.toml file.
+ *
+ * @param domain Domain to find a federation server for
+ * @return FederationServer
+ * @throws ConnectionErrorException Connection problems
+ * @throws NoFederationServerException Stellar.toml does not contain federation server info
+ * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
+ * @throws StellarTomlNotFoundInvalidException Stellar.toml file was not found or was malformed.
+ * @see Stellar.toml docs
+ */
+ public static FederationServer createForDomain(String domain) {
+ URI stellarTomlUri;
+ try {
+ StringBuilder uriBuilder = new StringBuilder();
+ uriBuilder.append("https://");
+ uriBuilder.append(domain);
+ uriBuilder.append("/.well-known/stellar.toml");
+ stellarTomlUri = new URI(uriBuilder.toString());
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ Toml stellarToml = null;
+ try {
+ Request request = new Request.Builder().get()
+ .url(stellarTomlUri.toString())
+ .build();
+ Response response = httpClient.newCall(request)
+ .execute();
+ if (response.code() >= 300) {
+ throw new StellarTomlNotFoundInvalidException();
+ }
+ ResponseBody body = response.body();
+ if (body == null) {
+ throw new StellarTomlNotFoundInvalidException();
+ }
+ stellarToml = new Toml().read(body.string());
+ } catch (IOException e) {
+ throw new ConnectionErrorException();
+ }
+
+ String federationServer = stellarToml.getString("FEDERATION_SERVER");
+ if (federationServer == null) {
+ throw new NoFederationServerException();
+ }
+
+ return new FederationServer(federationServer, domain);
}
- Toml stellarToml = null;
- try {
- Request request = new Request.Builder().get()
- .url(stellarTomlUri.toString())
- .build();
- Response response = httpClient.newCall(request)
- .execute();
- if (response.code() >= 300) {
- throw new StellarTomlNotFoundInvalidException();
- }
- ResponseBody body = response.body();
- if (body == null) {
- throw new StellarTomlNotFoundInvalidException();
- }
- stellarToml = new Toml().read(body.string());
- } catch (IOException e) {
- throw new ConnectionErrorException();
+
+ /**
+ * Resolves a stellar address using a given federation server.
+ *
+ * @param address Stellar addres, like bob*stellar.org
+ * @return FederationResponse
+ * @throws MalformedAddressException Address is malformed
+ * @throws ConnectionErrorException Connection problems
+ * @throws NotFoundException Stellar address not found by federation server
+ * @throws ServerErrorException Federation server responded with error
+ */
+ public FederationResponse resolveAddress(String address) {
+ String[] tokens = address.split("\\*");
+ if (tokens.length != 2) {
+ throw new MalformedAddressException();
+ }
+
+ URL uri = HttpUrl.parse(serverUri.toString()).newBuilder()
+ .addQueryParameter("type", "name")
+ .addQueryParameter("q", address)
+ .build().url();
+
+ TypeToken type = new TypeTokenbob*stellar.org
- * @return FederationResponse
- * @throws MalformedAddressException Address is malformed
- * @throws ConnectionErrorException Connection problems
- * @throws NotFoundException Stellar address not found by federation server
- * @throws ServerErrorException Federation server responded with error
- */
- public FederationResponse resolveAddress(String address) {
- String[] tokens = address.split("\\*");
- if (tokens.length != 2) {
- throw new MalformedAddressException();
+ /**
+ * Returns a domain this server is responsible for.
+ *
+ * @return InternetDomainName
+ */
+ public String getDomain() {
+ return domain;
}
- Uri uri = Uri.parse(serverUri.toString())
- .buildUpon()
- .appendQueryParameter("type", "name")
- .appendQueryParameter("q", address)
- .build();
-
- TypeToken type = new TypeTokenuri and returns {@link AccountResponse}.
- * This method is helpful for getting the links.
- * @throws IOException
- */
- public AccountResponse account(URI uri) throws IOException {
- TypeToken type = new TypeTokenGET /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());
- }
-
+ public AccountsRequestBuilder(OkHttpClient httpClient, URI 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(URI uri) throws IOException {
+ TypeToken type = new TypeTokenGET /accounts/{account}
+ *
+ * @param account Account to fetch
+ * @throws IOException
+ * @see Account Details
+ */
+ public AccountResponse account(KeyPair account) throws IOException {
+ this.setSegments("accounts", account.getAccountId());
+ return this.account(this.buildUri());
+ }
+
+<<<<<<< HEAD
/**
* Requests GET /accounts/{account}/aggregate_balance
*
@@ -101,48 +112,78 @@ public static Pageclose() connection when not needed anymore
- */
- public ServerSentEvent stream(final EventListenerkeypair field.
- * @return {@link Page} of {@link AccountResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Pageuri 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 Pageclose() connection when not needed anymore
+ * @see Server-Sent Events
+ * @see Response Format documentation
+ */
+ @Override
+ public keypair field.
+ *
+ * @return {@link Page} of {@link AccountResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public PageGET /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 Pageclose() connection when not needed anymore
- */
- public ServerSentEvent stream(final EventListenerGET /accounts/{account}/effects
+ *
+ * @param account Account for which to get effects
+ * @see Effects for Account
+ */
+ 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
+ *
+ * @param ledgerSeq Ledger for which to get effects
+ * @see Effects for Ledger
+ */
+ public EffectsRequestBuilder forLedger(long ledgerSeq) {
+ this.setSegments("ledgers", String.valueOf(ledgerSeq), "effects");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /transactions/{transactionId}/effects
+ *
+ * @param transactionId Transaction ID for which to get effects
+ * @see Effect for Transaction
+ */
+ 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
+ *
+ * @param operationId Operation ID for which to get effects
+ * @see Effect for Operation
+ */
+ 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 Pageclose() connection when not needed anymore
+ * @see Server-Sent Events
+ * @see Response Format documentation
+ */
+ @Override
+ public stream method.
*/
public interface EventListeneruri and returns {@link LedgerResponse}.
+ * This method is helpful for getting the links.
+ *
+ * @throws IOException
+ */
+ public LedgerResponse ledger(URI uri) throws IOException {
+ TypeToken type = new TypeTokenuri and returns {@link LedgerResponse}.
- * This method is helpful for getting the links.
- * @throws IOException
- */
- public LedgerResponse ledger(URI uri) throws IOException {
- TypeToken type = new TypeTokenGET /ledgers/{ledgerSeq}
+ *
+ * @param ledgerSeq Ledger to fetch
+ * @throws IOException
+ * @see Ledger Details
+ */
+ public LedgerResponse ledger(long ledgerSeq) throws IOException {
+ this.setSegments("ledgers", String.valueOf(ledgerSeq));
+ return this.ledger(this.buildUri());
+ }
- /**
- * 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 Pageuri 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 Pageclose() connection when not needed anymore
- */
- public ServerSentEvent stream(final EventListenerclose() connection when not needed anymore
+ * @see Server-Sent Events
+ * @see Response Format documentation
+ */
+ @Override
+ public