Skip to content

Commit

Permalink
Remove unnecessary to/fromBase64 code and use the one from the xdr pa…
Browse files Browse the repository at this point in the history
…ckage.
  • Loading branch information
overcat committed Aug 9, 2023
1 parent b7df35d commit 8508332
Show file tree
Hide file tree
Showing 9 changed files with 57 additions and 195 deletions.
34 changes: 9 additions & 25 deletions src/main/java/org/stellar/sdk/AbstractTransaction.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

import com.google.common.collect.ImmutableList;
import com.google.common.io.BaseEncoding;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
Expand All @@ -15,8 +13,6 @@
import org.stellar.sdk.xdr.SignatureHint;
import org.stellar.sdk.xdr.TransactionEnvelope;
import org.stellar.sdk.xdr.TransactionSignaturePayload;
import org.stellar.sdk.xdr.XdrDataInputStream;
import org.stellar.sdk.xdr.XdrDataOutputStream;

public abstract class AbstractTransaction {
protected final Network mNetwork;
Expand Down Expand Up @@ -120,13 +116,7 @@ public void addSignature(DecoratedSignature signature) {
*/
public String toEnvelopeXdrBase64() {
try {
TransactionEnvelope envelope = this.toEnvelopeXdr();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream);
TransactionEnvelope.encode(xdrOutputStream, envelope);

BaseEncoding base64Encoding = BaseEncoding.base64();
return base64Encoding.encode(outputStream.toByteArray());
return this.toEnvelopeXdr().toXdrBase64();
} catch (IOException e) {
throw new AssertionError(e);
}
Expand Down Expand Up @@ -176,11 +166,7 @@ public static AbstractTransaction fromEnvelopeXdr(TransactionEnvelope envelope,
*/
public static AbstractTransaction fromEnvelopeXdr(
AccountConverter accountConverter, String envelope, Network network) throws IOException {
BaseEncoding base64Encoding = BaseEncoding.base64();
byte[] bytes = base64Encoding.decode(envelope);

TransactionEnvelope transactionEnvelope =
TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
TransactionEnvelope transactionEnvelope = TransactionEnvelope.fromXdrBase64(envelope);
return fromEnvelopeXdr(accountConverter, transactionEnvelope, network);
}

Expand All @@ -201,15 +187,13 @@ public static byte[] getTransactionSignatureBase(
TransactionSignaturePayload.TransactionSignaturePayloadTaggedTransaction taggedTransaction,
Network network) {
try {
TransactionSignaturePayload payload = new TransactionSignaturePayload();
Hash hash = new Hash();
hash.setHash(network.getNetworkId());
payload.setNetworkId(hash);
payload.setTaggedTransaction(taggedTransaction);
ByteArrayOutputStream txOutputStream = new ByteArrayOutputStream();
XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(txOutputStream);
payload.encode(xdrOutputStream);
return txOutputStream.toByteArray();
Hash networkIdHash = new Hash(network.getNetworkId());
TransactionSignaturePayload payload =
new TransactionSignaturePayload.Builder()
.networkId(networkIdHash)
.taggedTransaction(taggedTransaction)
.build();
return payload.toXdrByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
Expand Down
10 changes: 1 addition & 9 deletions src/main/java/org/stellar/sdk/Operation.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.io.BaseEncoding;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import org.stellar.sdk.xdr.XdrDataOutputStream;

/** Abstract class for operations. */
@SuperBuilder(toBuilder = true)
Expand Down Expand Up @@ -51,12 +48,7 @@ public org.stellar.sdk.xdr.Operation toXdr() {
/** Returns base64-encoded Operation XDR object. */
public String toXdrBase64(AccountConverter accountConverter) {
try {
org.stellar.sdk.xdr.Operation operation = this.toXdr(accountConverter);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream);
org.stellar.sdk.xdr.Operation.encode(xdrOutputStream, operation);
BaseEncoding base64Encoding = BaseEncoding.base64();
return base64Encoding.encode(outputStream.toByteArray());
return toXdr(accountConverter).toXdrBase64();
} catch (IOException e) {
throw new AssertionError(e);
}
Expand Down
82 changes: 30 additions & 52 deletions src/main/java/org/stellar/sdk/SorobanServer.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package org.stellar.sdk;

import com.google.common.io.BaseEncoding;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
Expand All @@ -14,7 +11,6 @@
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
Expand Down Expand Up @@ -48,8 +44,6 @@
import org.stellar.sdk.xdr.SCVal;
import org.stellar.sdk.xdr.SorobanAuthorizationEntry;
import org.stellar.sdk.xdr.SorobanTransactionData;
import org.stellar.sdk.xdr.XdrDataInputStream;
import org.stellar.sdk.xdr.XdrDataOutputStream;

/**
* Main class used to connect to the Soroban-RPC instance and exposes an interface for requests to
Expand Down Expand Up @@ -122,8 +116,12 @@ public TransactionBuilderAccount getAccount(String accountId)
if (entries == null || entries.isEmpty()) {
throw new AccountNotFoundException(accountId);
}
LedgerEntry.LedgerEntryData ledgerEntryData =
ledgerEntryDataFromXdrBase64(entries.get(0).getXdr());
LedgerEntry.LedgerEntryData ledgerEntryData;
try {
ledgerEntryData = LedgerEntry.LedgerEntryData.fromXdrBase64(entries.get(0).getXdr());
} catch (IOException e) {
throw new IllegalArgumentException("invalid ledgerEntryData: " + entries.get(0).getXdr(), e);
}
long sequence = ledgerEntryData.getAccount().getSeqNum().getSequenceNumber().getInt64();
return new Account(accountId, sequence);
}
Expand Down Expand Up @@ -215,13 +213,21 @@ public Optional<GetLedgerEntriesResponse.LedgerEntryResult> getContractData(
* @throws SorobanRpcErrorResponse If the Soroban-RPC instance returns an error response.
*/
public GetLedgerEntriesResponse getLedgerEntries(Collection<LedgerKey> keys)
throws IOException, SorobanRpcErrorResponse {
throws SorobanRpcErrorResponse, IOException {
if (keys.isEmpty()) {
throw new IllegalArgumentException("At least one key must be provided.");
}

List<String> xdrKeys =
keys.stream().map(SorobanServer::ledgerKeyToXdrBase64).collect(Collectors.toList());
List<String> xdrKeys = new ArrayList<>();
for (LedgerKey key : keys) {
String xdrBase64;
try {
xdrBase64 = key.toXdrBase64();
} catch (IOException e) {
throw new IllegalArgumentException("invalid ledgerKey: " + key, e);
}
xdrKeys.add(xdrBase64);
}
GetLedgerEntriesRequest params = new GetLedgerEntriesRequest(xdrKeys);
return this.sendRequest(
"getLedgerEntries",
Expand Down Expand Up @@ -421,7 +427,11 @@ private Transaction assembleTransaction(
List<SorobanAuthorizationEntry> newEntries = new ArrayList<>(originalEntries);
if (simulateHostFunctionResult.getAuth() != null) {
for (String auth : simulateHostFunctionResult.getAuth()) {
newEntries.add(sorobanAuthorizationEntryFromXdrBase64(auth));
try {
newEntries.add(SorobanAuthorizationEntry.fromXdrBase64(auth));
} catch (IOException e) {
throw new IllegalArgumentException("invalid auth: " + auth, e);
}
}
}
operation =
Expand All @@ -432,8 +442,14 @@ private Transaction assembleTransaction(
.build();
}

SorobanTransactionData sorobanData =
Util.sorobanTransactionDataToXDR(simulateTransactionResponse.getTransactionData());
SorobanTransactionData sorobanData;
try {
sorobanData =
SorobanTransactionData.fromXdrBase64(simulateTransactionResponse.getTransactionData());
} catch (IOException e) {
throw new IllegalArgumentException(
"invalid transactionData: " + simulateTransactionResponse.getTransactionData(), e);
}

return new Transaction(
transaction.getAccountConverter(),
Expand Down Expand Up @@ -477,44 +493,6 @@ private static String generateRequestId() {
return UUID.randomUUID().toString();
}

private static String ledgerKeyToXdrBase64(LedgerKey ledgerKey) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
XdrDataOutputStream xdrDataOutputStream = new XdrDataOutputStream(byteArrayOutputStream);
try {
ledgerKey.encode(xdrDataOutputStream);
} catch (IOException e) {
throw new IllegalArgumentException("invalid ledgerKey.", e);
}
BaseEncoding base64Encoding = BaseEncoding.base64();
return base64Encoding.encode(byteArrayOutputStream.toByteArray());
}

private static LedgerEntry.LedgerEntryData ledgerEntryDataFromXdrBase64(String ledgerEntryData) {
BaseEncoding base64Encoding = BaseEncoding.base64();
byte[] bytes = base64Encoding.decode(ledgerEntryData);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
XdrDataInputStream xdrInputStream = new XdrDataInputStream(inputStream);
try {
return LedgerEntry.LedgerEntryData.decode(xdrInputStream);
} catch (IOException e) {
throw new IllegalArgumentException("invalid ledgerEntryData: " + ledgerEntryData, e);
}
}

private static SorobanAuthorizationEntry sorobanAuthorizationEntryFromXdrBase64(
String sorobanAuthorizationEntry) {
BaseEncoding base64Encoding = BaseEncoding.base64();
byte[] bytes = base64Encoding.decode(sorobanAuthorizationEntry);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
XdrDataInputStream xdrInputStream = new XdrDataInputStream(inputStream);
try {
return SorobanAuthorizationEntry.decode(xdrInputStream);
} catch (IOException e) {
throw new IllegalArgumentException(
"invalid ledgerEntryData: " + sorobanAuthorizationEntry, e);
}
}

/**
* Represents the "durability keyspace" that this ledger key belongs to, check {@link
* SorobanServer#getContractData} for more details.
Expand Down
11 changes: 3 additions & 8 deletions src/main/java/org/stellar/sdk/StrKey.java
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,7 @@ public static AccountID encodeToXDRAccountId(String data) {
PublicKey publicKey = new PublicKey();
publicKey.setDiscriminant(PublicKeyType.PUBLIC_KEY_TYPE_ED25519);
try {
publicKey.setEd25519(
Uint256.decode(
new XdrDataInputStream(new ByteArrayInputStream(decodeStellarAccountId(data)))));
publicKey.setEd25519(Uint256.fromXdrByteArray(decodeStellarAccountId(data)));
} catch (IOException e) {
throw new IllegalArgumentException("invalid address: " + data, e);
}
Expand All @@ -118,9 +116,7 @@ public static MuxedAccount encodeToXDRMuxedAccount(String data) {
case ACCOUNT_ID:
muxed.setDiscriminant(CryptoKeyType.KEY_TYPE_ED25519);
try {
muxed.setEd25519(
Uint256.decode(
new XdrDataInputStream(new ByteArrayInputStream(decodeStellarAccountId(data)))));
muxed.setEd25519(Uint256.fromXdrByteArray(decodeStellarAccountId(data)));
} catch (IOException e) {
throw new IllegalArgumentException("invalid address: " + data, e);
}
Expand Down Expand Up @@ -176,8 +172,7 @@ public static SignedPayloadSigner decodeSignedPayload(char[] data) {
byte[] signedPayloadRaw = decodeCheck(VersionByte.SIGNED_PAYLOAD, data);

SignerKey.SignerKeyEd25519SignedPayload xdrPayloadSigner =
SignerKey.SignerKeyEd25519SignedPayload.decode(
new XdrDataInputStream(new ByteArrayInputStream(signedPayloadRaw)));
SignerKey.SignerKeyEd25519SignedPayload.fromXdrByteArray(signedPayloadRaw);

return new SignedPayloadSigner(
xdrPayloadSigner.getEd25519().getUint256(), xdrPayloadSigner.getPayload());
Expand Down
8 changes: 7 additions & 1 deletion src/main/java/org/stellar/sdk/TransactionBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import static org.stellar.sdk.TransactionPreconditions.TIMEOUT_INFINITE;

import com.google.common.base.Function;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
Expand Down Expand Up @@ -280,7 +281,12 @@ public TransactionBuilder setSorobanData(SorobanTransactionData sorobanData) {
* @return Builder object so you can chain methods.
*/
public TransactionBuilder setSorobanData(String sorobanData) {
SorobanTransactionData data = Util.sorobanTransactionDataToXDR(sorobanData);
SorobanTransactionData data;
try {
data = SorobanTransactionData.fromXdrBase64(sorobanData);
} catch (IOException e) {
throw new IllegalArgumentException("Invalid Soroban data: " + sorobanData, e);
}
return setSorobanData(data);
}
}
52 changes: 2 additions & 50 deletions src/main/java/org/stellar/sdk/Util.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
package org.stellar.sdk;

import com.google.common.io.BaseEncoding;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.stellar.sdk.xdr.ClaimableBalanceID;
import org.stellar.sdk.xdr.SorobanTransactionData;
import org.stellar.sdk.xdr.XdrDataInputStream;
import org.stellar.sdk.xdr.XdrDataOutputStream;

public class Util {

Expand Down Expand Up @@ -103,62 +98,19 @@ public static String getSdkVersion() {

public static ClaimableBalanceID claimableBalanceIdToXDR(String balanceId) {
byte[] balanceIdBytes = BaseEncoding.base16().lowerCase().decode(balanceId.toLowerCase());
XdrDataInputStream balanceIdXdrDataInputStream =
new XdrDataInputStream(new ByteArrayInputStream(balanceIdBytes));

try {
return ClaimableBalanceID.decode(balanceIdXdrDataInputStream);
return ClaimableBalanceID.fromXdrByteArray(balanceIdBytes);
} catch (IOException e) {
throw new IllegalArgumentException("invalid balanceId: " + balanceId, e);
}
}

public static String xdrToClaimableBalanceId(ClaimableBalanceID balanceId) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
XdrDataOutputStream xdrDataOutputStream = new XdrDataOutputStream(byteArrayOutputStream);
try {
balanceId.encode(xdrDataOutputStream);
return BaseEncoding.base16().lowerCase().encode(balanceId.toXdrByteArray());
} catch (IOException e) {
throw new IllegalArgumentException("invalid claimClaimableBalanceOp.", e);
}
return BaseEncoding.base16().lowerCase().encode(byteArrayOutputStream.toByteArray());
}

/**
* Convert {@link SorobanTransactionData} XDR String representation to {@link
* SorobanTransactionData} object.
*
* @param sorobanData XDR String representation of a {@link SorobanTransactionData}
* @return {@link SorobanTransactionData}
*/
public static SorobanTransactionData sorobanTransactionDataToXDR(String sorobanData) {
BaseEncoding base64Encoding = BaseEncoding.base64();
byte[] bytes = base64Encoding.decode(sorobanData);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
XdrDataInputStream xdrInputStream = new XdrDataInputStream(inputStream);
try {
return SorobanTransactionData.decode(xdrInputStream);
} catch (IOException e) {
throw new IllegalArgumentException("invalid sorobanData: " + sorobanData, e);
}
}

/**
* Convert {@link SorobanTransactionData} object to XDR String representation.
*
* @param sorobanData {@link SorobanTransactionData} object
* @return XDR String representation of a {@link SorobanTransactionData}
*/
public static String xdrToSorobanTransactionData(SorobanTransactionData sorobanData) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
XdrDataOutputStream xdrDataOutputStream = new XdrDataOutputStream(byteArrayOutputStream);
try {
sorobanData.encode(xdrDataOutputStream);
} catch (IOException e) {
throw new IllegalArgumentException("invalid sorobanData.", e);
}
BaseEncoding base64Encoding = BaseEncoding.base64();
return base64Encoding.encode(byteArrayOutputStream.toByteArray());
}

public static AssetTypeCreditAlphaNum assertNonNativeAsset(Asset asset) {
Expand Down
Loading

0 comments on commit 8508332

Please sign in to comment.