<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <maven.compiler.target>1.8</maven.compiler.target>
- <maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
package io.bytom.api;
-import io.bytom.common.Utils;
import io.bytom.types.*;
import java.io.IOException;
import java.util.Map;
}
}
- @Override
- public String toString() {
- return Utils.serializer.toJson(this);
- }
-
-
public AssetAmount getAssetAmount() {
return new AssetAmount(new AssetID(this.assetId), this.amount);
}
Hash assetDefHash = new Hash(this.rawAssetDefinition);
AssetAmount value = this.getAssetAmount();
- Issue issuance = new Issue(nonceHash, value, index);
Program pro = new Program(this.getVmVersion(), Hex.decode(this.getProgram()));
- issuance.assetDefinition = new AssetDefinition(assetDefHash, pro);
- return issuance;
+ return new Issue(nonceHash, value, index, new AssetDefinition(assetDefHash, pro));
}
@Override
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//assetVersion
Utils.writeVarint(1, stream);
- //写入 type nonce assetId amount
+
ByteArrayOutputStream issueInfo = new ByteArrayOutputStream();
- //写入 input.type==00 issue
Utils.writeVarint(ISSUANCE_INPUT_TYPE, issueInfo);
- //写入 8个字节的随机数
Utils.writeVarStr(Hex.decode(nonce), issueInfo);
issueInfo.write(Hex.decode(getAssetId()));
Utils.writeVarint(getAmount(), issueInfo);
stream.write(issueInfo.toByteArray());
ByteArrayOutputStream issueInfo1 = new ByteArrayOutputStream();
- //未知
Utils.writeVarint(1, issueInfo1);
- //写入assetDefine
Utils.writeVarStr(Hex.decode(rawAssetDefinition), issueInfo1);
- //vm.version
+ // vm version
Utils.writeVarint(1, issueInfo1);
- //controlProgram
Utils.writeVarStr(Hex.decode(getProgram()), issueInfo1);
//inputWitness
/**
* The number of units of the asset being controlled.
*/
- public Long amount;
+ private Long amount;
/**
* The id of the asset being controlled.
*/
- public String assetId;
+ private String assetId;
/**
* The control program which must be satisfied to transfer this output.
*/
- public String controlProgram;
+ private String controlProgram;
/**
* The id of the output.
*/
- public String id;
+ private String id;
/**
* The output's position in a transaction's list of outputs.
*/
- public Integer position;
+ private Integer position;
public Output(String assetId, Long amount, String controlProgram) {
this.assetId = assetId;
return id;
}
+ public void setId(String id) {
+ this.id = id;
+ }
+
public Integer getPosition() {
return position;
}
+++ /dev/null
-package io.bytom.api;\r
-\r
-import com.google.gson.annotations.SerializedName;\r
-import io.bytom.common.Utils;\r
-import io.bytom.exception.JSONException;\r
-\r
-/**\r
- * Receivers are used to facilitate payments between accounts on different\r
- * cores. They contain a control program and an expiration date. In the future,\r
- * more payment-related metadata may be placed here.\r
- * <p>\r
- * Receivers are typically created under accounts via the\r
- */\r
-public class Receiver {\r
-\r
- @SerializedName("address")\r
- public String address;\r
- /**\r
- * Hex-encoded string representation of the control program.\r
- */\r
- @SerializedName("control_program")\r
- public String controlProgram;\r
-\r
-\r
- /**\r
- * Serializes the receiver into a form that is safe to transfer over the wire.\r
- *\r
- * @return the JSON-serialized representation of the Receiver object\r
- */\r
- public String toJson() {\r
- return Utils.serializer.toJson(this);\r
- }\r
-\r
- /**\r
- * Deserializes a Receiver from JSON.\r
- *\r
- * @param json a JSON-serialized Receiver object\r
- * @return the deserialized Receiver object\r
- * @throws JSONException Raised if the provided string is not valid JSON.\r
- */\r
- public static Receiver fromJson(String json) throws JSONException {\r
- try {\r
- return Utils.serializer.fromJson(json, Receiver.class);\r
- } catch (IllegalStateException e) {\r
- throw new JSONException("Unable to parse serialized receiver: " + e.getMessage());\r
- }\r
- }\r
-}\r
+++ /dev/null
-package io.bytom.api;\r
-\r
-import io.bytom.common.Utils;\r
-import io.bytom.exception.BytomException;\r
-import io.bytom.http.Client;\r
-\r
-import java.util.HashMap;\r
-\r
-public class SubmitTransaction {\r
-\r
- public static SubmitResponse submitRawTransaction(Client client, String rawTransaction) throws BytomException {\r
- HashMap<String, Object> body = new HashMap<>();\r
- body.put("raw_transaction", rawTransaction);\r
- return client.request("submit-transaction", body, SubmitResponse.class);\r
- }\r
-\r
- public static class SubmitResponse {\r
- /**\r
- * The transaction id.\r
- */\r
- public String tx_id;\r
-\r
- public String toJson() {\r
- return Utils.serializer.toJson(this);\r
- }\r
-\r
- }\r
-}\r
this.timeRange = builder.timeRange;\r
\r
this.validate();\r
- this.mapTransaction();\r
+ this.mapTx();\r
this.sign();\r
}\r
\r
throw new IllegalArgumentException("the size range of transaction must be specified.");\r
}\r
\r
- inputs.forEach(BaseInput::validate);\r
+ for (BaseInput input : inputs) {\r
+ input.validate();\r
+ }\r
}\r
\r
- private void mapTransaction() {\r
+ private void mapTx() {\r
Map<Hash, Entry> entryMap = new HashMap<>();\r
ValueSource[] muxSources = new ValueSource[inputs.size()];\r
List<InputEntry> inputEntries = new ArrayList<>();\r
Mux mux = new Mux(muxSources, new Program(1, new byte[]{0x51}));\r
Hash muxID = addEntry(entryMap, mux);\r
for (InputEntry inputEntry : inputEntries) {\r
- inputEntry.setDestination(muxID, inputEntry.ordinal, entryMap);\r
+ inputEntry.setDestination(muxID, inputEntry.getOrdinal(), entryMap);\r
}\r
\r
List<Hash> resultIDList = new ArrayList<>();\r
for (int i = 0; i < outputs.size(); i++) {\r
Output output = outputs.get(i);\r
\r
- AssetAmount amount = new AssetAmount(new AssetID(output.assetId), output.amount);\r
+ AssetAmount amount = new AssetAmount(new AssetID(output.getAssetId()), output.getAmount());\r
ValueSource src = new ValueSource(muxID, amount, i);\r
\r
Hash resultID;\r
- if (output.controlProgram.startsWith("6a")) {\r
+ if (output.getControlProgram().startsWith("6a")) {\r
Retirement retirement = new Retirement(src, i);\r
resultID = addEntry(entryMap, retirement);\r
} else {\r
- Program prog = new Program(1, Hex.decode(output.controlProgram));\r
- OutputEntry oup = new OutputEntry(src, prog, i);\r
+ Program program = new Program(1, Hex.decode(output.getControlProgram()));\r
+ OutputEntry oup = new OutputEntry(src, program, i);\r
resultID = addEntry(entryMap, oup);\r
}\r
\r
resultIDList.add(resultID);\r
- output.id = resultID.toString();\r
+ output.setId(resultID.toString());\r
\r
- ValueDestination destination = new ValueDestination(resultID, src.value, 0);\r
- mux.witnessDestinations.add(destination);\r
+ ValueDestination destination = new ValueDestination(resultID, src.getValue(), 0);\r
+ mux.getWitnessDestinations().add(destination);\r
}\r
\r
TxHeader txHeader = new TxHeader(version, size, timeRange, resultIDList.toArray(new Hash[]{}));\r
--- /dev/null
+package io.bytom.exception;
+
+public class WriteForHashException extends RuntimeException {
+
+ public WriteForHashException() {
+ super();
+ }
+
+ public WriteForHashException(String message) {
+ super(message);
+ }
+
+ public WriteForHashException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+
+ public WriteForHashException(Throwable cause) {
+ super(cause);
+ }
+}
+++ /dev/null
-package io.bytom.http;\r
-\r
-import io.bytom.common.Utils;\r
-import io.bytom.exception.BytomException;\r
-\r
-import java.util.*;\r
-\r
-/**\r
- * BatchResponse provides a convenient interface for handling the results of\r
- * batched API calls. The response contains one success or error per outgoing\r
- * request item in the batch. Errors are always of type BytomException.\r
- */\r
-public class BatchResponse<T> {\r
- private Map<Integer, T> successesByIndex = new LinkedHashMap<>();\r
- private Map<Integer, BytomException> errorsByIndex = new LinkedHashMap<>();\r
-\r
- public String toJson() {\r
- return Utils.serializer.toJson(this);\r
- }\r
-\r
- /**\r
- * This constructor is used for synthetically generating a batch response\r
- * object from a map of successes and a map of errors. It ensures that\r
- * the successes and errors are stored in an order-preserving fashion.\r
- */\r
- public BatchResponse(Map<Integer, T> successes, Map<Integer, BytomException> errors) {\r
- List<Integer> successIndexes = new ArrayList<>();\r
- Iterator<Integer> successIter = successes.keySet().iterator();\r
- while (successIter.hasNext()) {\r
- successIndexes.add(successIter.next());\r
- }\r
- Collections.sort(successIndexes);\r
-\r
- for (int i : successIndexes) {\r
- successesByIndex.put(i, successes.get(i));\r
- }\r
-\r
- List<Integer> errorIndexes = new ArrayList<>();\r
- Iterator<Integer> errorIter = errors.keySet().iterator();\r
- while (errorIter.hasNext()) {\r
- errorIndexes.add(errorIter.next());\r
- }\r
- Collections.sort(errorIndexes);\r
- for (int i : errorIndexes) {\r
- errorsByIndex.put(i, errors.get(i));\r
- }\r
- }\r
-\r
- /**\r
- * Returns the total number of response objects. This should equal the number\r
- * of request objects in the batch.\r
- */\r
- public int size() {\r
- return successesByIndex.size() + errorsByIndex.size();\r
- }\r
-\r
- /**\r
- * Returns whether the request object at the given index produced a success.\r
- *\r
- * @param index the index of the request object\r
- */\r
- public boolean isSuccess(int index) {\r
- return successesByIndex.containsKey(index);\r
- }\r
-\r
- /**\r
- * Returns whether the request object at the given index produced an error.\r
- *\r
- * @param index the index of the request object\r
- */\r
- public boolean isError(int index) {\r
- return errorsByIndex.containsKey(index);\r
- }\r
-\r
- /**\r
- * Returns a list of successful response objects in the batch. The order of\r
- * the list corresponds to the order of the request objects that produced the\r
- * successes.\r
- */\r
- public List<T> successes() {\r
- List<T> res = new ArrayList<>();\r
- res.addAll(successesByIndex.values());\r
- return res;\r
- }\r
-\r
- /**\r
- * Returns a list of error objects in the batch. The order of the list\r
- * corresponds to the order of the request objects that produced the\r
- * errors.\r
- */\r
- public List<BytomException> errors() {\r
- List<BytomException> res = new ArrayList<>();\r
- res.addAll(errorsByIndex.values());\r
- return res;\r
- }\r
-\r
- /**\r
- * Returns a map of success responses, keyed by the index of the request\r
- * object that produced the success. The set of this map's keys is mutually\r
- * exclusive of the keys returned by errorsByIndex.\r
- */\r
- public Map<Integer, T> successesByIndex() {\r
- return successesByIndex;\r
- }\r
-\r
- /**\r
- * Returns a map of error responses, keyed by the index of the request\r
- * object that produced the error. The set of this map's keys is mutually\r
- * exclusive of the keys returned by successByIndex.\r
- */\r
- public Map<Integer, BytomException> errorsByIndex() {\r
- return errorsByIndex;\r
- }\r
-}\r
+++ /dev/null
-package io.bytom.http;\r
-\r
-import com.google.gson.Gson;\r
-import com.google.gson.JsonElement;\r
-import com.google.gson.JsonParser;\r
-import com.squareup.okhttp.*;\r
-import io.bytom.common.Configuration;\r
-import io.bytom.common.Utils;\r
-import io.bytom.exception.APIException;\r
-import io.bytom.exception.BytomException;\r
-import io.bytom.exception.ConfigurationException;\r
-import io.bytom.exception.JSONException;\r
-import org.apache.log4j.Logger;\r
-import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;\r
-\r
-import javax.net.ssl.*;\r
-import java.io.*;\r
-import java.lang.reflect.Type;\r
-import java.net.MalformedURLException;\r
-import java.net.Proxy;\r
-import java.net.URL;\r
-import java.nio.file.Files;\r
-import java.nio.file.Paths;\r
-import java.security.GeneralSecurityException;\r
-import java.security.KeyFactory;\r
-import java.security.KeyStore;\r
-import java.security.cert.Certificate;\r
-import java.security.cert.CertificateFactory;\r
-import java.security.cert.X509Certificate;\r
-import java.security.spec.KeySpec;\r
-import java.security.spec.PKCS8EncodedKeySpec;\r
-import java.util.Arrays;\r
-import java.util.Collection;\r
-import java.util.Objects;\r
-import java.util.Random;\r
-import java.util.concurrent.TimeUnit;\r
-\r
-/**\r
- * The Client object contains all information necessary to\r
- * perform an HTTP request against a remote API. Typically,\r
- * an application will have a client that makes requests to\r
- * a Chain Core, and a separate Client that makes requests\r
- * to an HSM server.\r
- */\r
-public class Client {\r
- private String url;\r
- private String accessToken;\r
- private OkHttpClient httpClient;\r
-\r
- // Used to create empty, in-memory key stores.\r
- private static final char[] DEFAULT_KEYSTORE_PASSWORD = "123456".toCharArray();\r
- private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");\r
- private static String version = "dev"; // updated in the static initializer\r
-\r
- public static Logger logger = Logger.getLogger(Client.class);\r
-\r
- private static class BuildProperties {\r
- public String version;\r
- }\r
-\r
- static {\r
- InputStream in = Client.class.getClassLoader().getResourceAsStream("properties.json");\r
- if (in != null) {\r
- InputStreamReader inr = new InputStreamReader(in);\r
- version = Utils.serializer.fromJson(inr, BuildProperties.class).version;\r
- }\r
- }\r
-\r
- public static Client generateClient() throws BytomException {\r
-\r
- String coreURL = Configuration.getValue("bytom.api.url");\r
- String accessToken = Configuration.getValue("client.access.token");\r
-\r
- if (coreURL == null || coreURL.isEmpty()) {\r
- coreURL = "http://47.91.254.104:8888";\r
- }\r
-\r
- if (coreURL.endsWith("/")) {\r
- //split the last char "/"\r
- coreURL = coreURL.substring(0, coreURL.length() - 1);\r
- logger.info("check the coreURL is right.");\r
- }\r
-\r
- return new Client(coreURL, accessToken);\r
- }\r
-\r
- public Client(Builder builder) throws ConfigurationException {\r
- if (builder.url.endsWith("/")) {\r
- //split the last char "/"\r
- builder.url = builder.url.substring(0, builder.url.length() - 1);\r
- }\r
- this.url = builder.url;\r
- this.accessToken = builder.accessToken;\r
- this.httpClient = buildHttpClient(builder);\r
- }\r
-\r
- /**\r
- * Create a new http Client object using the default development host URL.\r
- */\r
- public Client() throws BytomException {\r
- this(new Builder());\r
- }\r
-\r
- /**\r
- * Create a new http Client object\r
- *\r
- * @param url the URL of the Chain Core or HSM\r
- */\r
- public Client(String url) throws BytomException {\r
- this(new Builder().setUrl(url));\r
- }\r
-\r
- /**\r
- * Create a new http Client object\r
- *\r
- * @param url the URL of the Chain Core or HSM\r
- * @param accessToken a Client API access token\r
- */\r
- public Client(String url, String accessToken) throws BytomException {\r
- this(new Builder().setUrl(url).setAccessToken(accessToken));\r
- }\r
-\r
- /**\r
- * Perform a single HTTP POST request against the API for a specific action.\r
- *\r
- * @param action The requested API action\r
- * @param body Body payload sent to the API as JSON\r
- * @param tClass Type of object to be deserialized from the response JSON\r
- * @return the result of the post request\r
- * @throws BytomException\r
- */\r
- public <T> T request(String action, Object body, final Type tClass) throws BytomException {\r
- ResponseCreator<T> rc =\r
- new ResponseCreator<T>() {\r
- public T create(Response response, Gson deserializer) throws IOException, BytomException {\r
- JsonElement root = new JsonParser().parse(response.body().charStream());\r
- JsonElement status = root.getAsJsonObject().get("status");\r
- JsonElement data = root.getAsJsonObject().get("data");\r
- if (status != null && status.toString().contains("fail")) {\r
- throw new BytomException(root.getAsJsonObject().get("msg").toString());\r
- } else if (data != null) {\r
- return deserializer.fromJson(data, tClass);\r
- } else {\r
- return deserializer.fromJson(response.body().charStream(), tClass);\r
- }\r
- }\r
- };\r
- return post(action, body, rc);\r
- }\r
-\r
- /**\r
- * Perform a single HTTP POST request against the API for a specific action,\r
- * ignoring the body of the response.\r
- *\r
- * @param action The requested API action\r
- * @param body Body payload sent to the API as JSON\r
- * @throws BytomException\r
- */\r
- public void request(String action, Object body) throws BytomException {\r
- ResponseCreator<Object> rc =\r
- new ResponseCreator<Object>() {\r
- public Object create(Response response, Gson deserializer) throws IOException, BytomException {\r
- JsonElement root = new JsonParser().parse(response.body().charStream());\r
- JsonElement status = root.getAsJsonObject().get("status");\r
- JsonElement data = root.getAsJsonObject().get("data");\r
- if (status != null && status.toString().contains("fail")) {\r
- throw new BytomException(root.getAsJsonObject().get("msg").toString());\r
- }\r
- return null;\r
- }\r
- };\r
- post(action, body, rc);\r
- }\r
-\r
- /**\r
- * return the value of named as key from json\r
- *\r
- * @param action\r
- * @param body\r
- * @param key\r
- * @param tClass\r
- * @param <T>\r
- * @return\r
- * @throws BytomException\r
- */\r
- public <T> T requestGet(String action, Object body, final String key, final Type tClass)\r
- throws BytomException {\r
- ResponseCreator<T> rc = new ResponseCreator<T>() {\r
- public T create(Response response, Gson deserializer) throws IOException,\r
- BytomException {\r
- JsonElement root = new JsonParser().parse(response.body().charStream());\r
- JsonElement status = root.getAsJsonObject().get("status");\r
- JsonElement data = root.getAsJsonObject().get("data");\r
-\r
- if (status != null && status.toString().contains("fail"))\r
- throw new BytomException(root.getAsJsonObject().get("msg").toString());\r
- else if (data != null)\r
- return deserializer.fromJson(data.getAsJsonObject().get(key), tClass);\r
- else\r
- return deserializer.fromJson(response.body().charStream(), tClass);\r
- }\r
- };\r
- return post(action, body, rc);\r
- }\r
-\r
- /**\r
- * Perform a single HTTP POST request against the API for a specific action.\r
- * Use this method if you want batch semantics, i.e., the endpoint response\r
- * is an array of valid objects interleaved with arrays, once corresponding to\r
- * each input object.\r
- *\r
- * @param action The requested API action\r
- * @param body Body payload sent to the API as JSON\r
- * @param tClass Type of object to be deserialized from the response JSON\r
- * @return the result of the post request\r
- * @throws BytomException\r
- */\r
- /*\r
- public <T> T requestBatch(String action, Object body, final Type tClass) throws BytomException {\r
- ResponseCreator<T> rc =\r
- new ResponseCreator<T>() {\r
- public T create(Response response, Gson deserializer) throws IOException, BytomException {\r
- JsonElement root = new JsonParser().parse(response.body().charStream());\r
- JsonElement status = root.getAsJsonObject().get("status");\r
- JsonElement data = root.getAsJsonObject().get("data");\r
- if (status != null && status.toString().contains("fail")) {\r
- throw new BytomException(root.getAsJsonObject().get("msg").toString());\r
- } else if (data != null) {\r
- return deserializer.fromJson(data, tClass);\r
- } else {\r
- return deserializer.fromJson(response.body().charStream(), tClass);\r
- }\r
- }\r
- };\r
- //把object转换为json对象数组(有点难)\r
-\r
- //根据数组的大小循环调用post()方法\r
-\r
- //重写create()接口方法,对成功和失败做不同的处理\r
-\r
- //调用BatchResponse(Map<Integer, T> successes, Map<Integer, APIException> errors)\r
- //构造方法,最后返回BatchResponse实例对象\r
-\r
- return post(action, body, rc);\r
- }\r
- */\r
-\r
-\r
- /**\r
- * Returns true if a client access token stored in the client.\r
- *\r
- * @return a boolean\r
- */\r
- public boolean hasAccessToken() {\r
- return this.accessToken != null && !this.accessToken.isEmpty();\r
- }\r
-\r
- /**\r
- * Returns the client access token (possibly null).\r
- *\r
- * @return the client access token\r
- */\r
- public String accessToken() {\r
- return accessToken;\r
- }\r
-\r
- public String getUrl() {\r
- return url;\r
- }\r
-\r
- /**\r
- * Pins a public key to the HTTP client.\r
- *\r
- * @param provider certificate provider\r
- * @param subjPubKeyInfoHash public key hash\r
- */\r
- public void pinCertificate(String provider, String subjPubKeyInfoHash) {\r
- CertificatePinner cp =\r
- new CertificatePinner.Builder().add(provider, subjPubKeyInfoHash).build();\r
- this.httpClient.setCertificatePinner(cp);\r
- }\r
-\r
- /**\r
- * Sets the default connect timeout for new connections. A value of 0 means no timeout.\r
- *\r
- * @param timeout the number of time units for the default timeout\r
- * @param unit the unit of time\r
- */\r
- public void setConnectTimeout(long timeout, TimeUnit unit) {\r
- this.httpClient.setConnectTimeout(timeout, unit);\r
- }\r
-\r
- /**\r
- * Sets the default read timeout for new connections. A value of 0 means no timeout.\r
- *\r
- * @param timeout the number of time units for the default timeout\r
- * @param unit the unit of time\r
- */\r
- public void setReadTimeout(long timeout, TimeUnit unit) {\r
- this.httpClient.setReadTimeout(timeout, unit);\r
- }\r
-\r
- /**\r
- * Sets the default write timeout for new connections. A value of 0 means no timeout.\r
- *\r
- * @param timeout the number of time units for the default timeout\r
- * @param unit the unit of time\r
- */\r
- public void setWriteTimeout(long timeout, TimeUnit unit) {\r
- this.httpClient.setWriteTimeout(timeout, unit);\r
- }\r
-\r
- /**\r
- * Sets the proxy information for the HTTP client.\r
- *\r
- * @param proxy proxy object\r
- */\r
- public void setProxy(Proxy proxy) {\r
- this.httpClient.setProxy(proxy);\r
- }\r
-\r
- /**\r
- * Defines an interface for deserializing HTTP responses into objects.\r
- *\r
- * @param <T> the type of object to return\r
- */\r
- public interface ResponseCreator<T> {\r
- /**\r
- * Deserializes an HTTP response into a Java object of type T.\r
- *\r
- * @param response HTTP response object\r
- * @param deserializer json deserializer\r
- * @return an object of type T\r
- * @throws BytomException\r
- * @throws IOException\r
- */\r
- T create(Response response, Gson deserializer) throws BytomException, IOException;\r
- }\r
-\r
- /**\r
- * Builds and executes an HTTP Post request.\r
- *\r
- * @param path the path to the endpoint\r
- * @param body the request body\r
- * @param respCreator object specifying the response structure\r
- * @return a response deserialized into type T\r
- * @throws BytomException\r
- */\r
- private <T> T post(String path, Object body, ResponseCreator<T> respCreator)\r
- throws BytomException {\r
-\r
- RequestBody requestBody = RequestBody.create(this.JSON, Utils.serializer.toJson(body));\r
- Request req;\r
-\r
- BytomException exception = null;\r
- URL endpointURL = null;\r
-\r
- try {\r
- endpointURL = new URL(url + "/" + path);\r
- } catch (MalformedURLException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- Request.Builder builder =\r
- new Request.Builder()\r
- .header("User-Agent", "bytom-sdk-java/" + version)\r
- .url(endpointURL)\r
- .method("POST", requestBody);\r
- if (hasAccessToken()) {\r
- builder = builder.header("Authorization", buildCredentials());\r
- }\r
- req = builder.build();\r
-\r
- Response resp = null;\r
-\r
- T object = null;\r
-\r
- try {\r
- resp = this.checkError(this.httpClient.newCall(req).execute());\r
- object = respCreator.create(resp, Utils.serializer);\r
- } catch (IOException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- return object;\r
- }\r
-\r
- private OkHttpClient buildHttpClient(Builder builder) throws ConfigurationException {\r
- OkHttpClient httpClient = builder.baseHttpClient.clone();\r
-\r
- try {\r
- if (builder.trustManagers != null) {\r
- SSLContext sslContext = SSLContext.getInstance("TLS");\r
- sslContext.init(builder.keyManagers, builder.trustManagers, null);\r
- httpClient.setSslSocketFactory(sslContext.getSocketFactory());\r
- }\r
- } catch (GeneralSecurityException ex) {\r
- throw new ConfigurationException("Unable to configure TLS", ex);\r
- }\r
- if (builder.readTimeoutUnit != null) {\r
- httpClient.setReadTimeout(builder.readTimeout, builder.readTimeoutUnit);\r
- }\r
- if (builder.writeTimeoutUnit != null) {\r
- httpClient.setWriteTimeout(builder.writeTimeout, builder.writeTimeoutUnit);\r
- }\r
- if (builder.connectTimeoutUnit != null) {\r
- httpClient.setConnectTimeout(builder.connectTimeout, builder.connectTimeoutUnit);\r
- }\r
- if (builder.pool != null) {\r
- httpClient.setConnectionPool(builder.pool);\r
- }\r
- if (builder.proxy != null) {\r
- httpClient.setProxy(builder.proxy);\r
- }\r
- if (builder.cp != null) {\r
- httpClient.setCertificatePinner(builder.cp);\r
- }\r
-\r
- return httpClient;\r
- }\r
-\r
- private static final Random randomGenerator = new Random();\r
- private static final int MAX_RETRIES = 10;\r
- private static final int RETRY_BASE_DELAY_MILLIS = 40;\r
-\r
- // the max amount of time cored leader election could take\r
- private static final int RETRY_MAX_DELAY_MILLIS = 15000;\r
-\r
- private static int retryDelayMillis(int retryAttempt) {\r
- // Calculate the max delay as base * 2 ^ (retryAttempt - 1).\r
- int max = RETRY_BASE_DELAY_MILLIS * (1 << (retryAttempt - 1));\r
- max = Math.min(max, RETRY_MAX_DELAY_MILLIS);\r
-\r
- // To incorporate jitter, use a pseudo random delay between [max/2, max] millis.\r
- return randomGenerator.nextInt(max / 2) + max / 2 + 1;\r
- }\r
-\r
- private static final int[] RETRIABLE_STATUS_CODES = {\r
- 408, // Request Timeout\r
- 429, // Too Many Requests\r
- 500, // Internal Server Error\r
- 502, // Bad Gateway\r
- 503, // Service Unavailable\r
- 504, // Gateway Timeout\r
- 509, // Bandwidth Limit Exceeded\r
- };\r
-\r
- private static boolean isRetriableStatusCode(int statusCode) {\r
- for (int i = 0; i < RETRIABLE_STATUS_CODES.length; i++) {\r
- if (RETRIABLE_STATUS_CODES[i] == statusCode) {\r
- return true;\r
- }\r
- }\r
- return false;\r
- }\r
-\r
- private Response checkError(Response response) throws BytomException {\r
- /*\r
- String rid = response.headers().get("Bytom-Request-ID");\r
- if (rid == null || rid.length() == 0) {\r
- // Header field Bytom-Request-ID is set by the backend\r
- // API server. If this field is set, then we can expect\r
- // the body to be well-formed JSON. If it's not set,\r
- // then we are probably talking to a gateway or proxy.\r
- throw new ConnectivityException(response);\r
- } */\r
-\r
- if ((response.code() / 100) != 2) {\r
- try {\r
- APIException err =\r
- Utils.serializer.fromJson(response.body().charStream(), APIException.class);\r
- if (err.code != null) {\r
- //err.requestId = rid;\r
- err.statusCode = response.code();\r
- throw err;\r
- }\r
- } catch (IOException ex) {\r
- //throw new JSONException("Unable to read body. " + ex.getMessage(), rid);\r
- throw new JSONException("Unable to read body. ");\r
- }\r
- }\r
- return response;\r
- }\r
-\r
- private String buildCredentials() {\r
- String user = "";\r
- String pass = "";\r
- if (hasAccessToken()) {\r
- String[] parts = accessToken.split(":");\r
- if (parts.length >= 1) {\r
- user = parts[0];\r
- }\r
- if (parts.length >= 2) {\r
- pass = parts[1];\r
- }\r
- }\r
- return Credentials.basic(user, pass);\r
- }\r
-\r
- /**\r
- * Overrides {@link Object#hashCode()}\r
- *\r
- * @return the hash code\r
- */\r
- @Override\r
- public int hashCode() {\r
- int code = this.url.hashCode();\r
- if (this.hasAccessToken()) {\r
- code = code * 31 + this.accessToken.hashCode();\r
- }\r
- return code;\r
- }\r
-\r
- /**\r
- * Overrides {@link Object#equals(Object)}\r
- *\r
- * @param o the object to compare\r
- * @return a boolean specifying equality\r
- */\r
- @Override\r
- public boolean equals(Object o) {\r
- if (o == null) return false;\r
- if (!(o instanceof Client)) return false;\r
-\r
- Client other = (Client) o;\r
- if (!this.url.equalsIgnoreCase(other.url)) {\r
- return false;\r
- }\r
- return Objects.equals(this.accessToken, other.accessToken);\r
- }\r
-\r
- /**\r
- * A builder class for creating client objects\r
- */\r
- public static class Builder {\r
-\r
- private String url;\r
-\r
- private OkHttpClient baseHttpClient;\r
- private String accessToken;\r
- private CertificatePinner cp;\r
- private KeyManager[] keyManagers;\r
- private TrustManager[] trustManagers;\r
- private long connectTimeout;\r
- private TimeUnit connectTimeoutUnit;\r
- private long readTimeout;\r
- private TimeUnit readTimeoutUnit;\r
- private long writeTimeout;\r
- private TimeUnit writeTimeoutUnit;\r
- private Proxy proxy;\r
- private ConnectionPool pool;\r
-\r
- public Builder() {\r
- this.baseHttpClient = new OkHttpClient();\r
- this.baseHttpClient.setFollowRedirects(false);\r
- this.setDefaults();\r
- }\r
-\r
- public Builder(Client client) {\r
- this.baseHttpClient = client.httpClient.clone();\r
- this.url = client.url;\r
- this.accessToken = client.accessToken;\r
- }\r
-\r
- private void setDefaults() {\r
- this.setReadTimeout(30, TimeUnit.SECONDS);\r
- this.setWriteTimeout(30, TimeUnit.SECONDS);\r
- this.setConnectTimeout(30, TimeUnit.SECONDS);\r
- this.setConnectionPool(50, 2, TimeUnit.MINUTES);\r
- }\r
-\r
- public Builder setUrl(String url) {\r
- this.url = url;\r
- return this;\r
- }\r
-\r
- /**\r
- * Sets the access token for the client\r
- *\r
- * @param accessToken The access token for the Chain Core or HSM\r
- */\r
- public Builder setAccessToken(String accessToken) {\r
- this.accessToken = accessToken;\r
- return this;\r
- }\r
-\r
-\r
- /**\r
- * Trusts the given CA certs, and no others. Use this if you are running\r
- * your own CA, or are using a self-signed server certificate.\r
- *\r
- * @param is input stream of the certificates to trust, in PEM format.\r
- */\r
- public Builder setTrustedCerts(InputStream is) throws ConfigurationException {\r
- try {\r
- // Extract certs from PEM-encoded input.\r
- CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");\r
- Collection<? extends Certificate> certificates =\r
- certificateFactory.generateCertificates(is);\r
- if (certificates.isEmpty()) {\r
- throw new IllegalArgumentException("expected non-empty set of trusted certificates");\r
- }\r
-\r
- // Create a new key store and input the cert.\r
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());\r
- keyStore.load(null, DEFAULT_KEYSTORE_PASSWORD);\r
- int index = 0;\r
- for (Certificate certificate : certificates) {\r
- String certificateAlias = Integer.toString(index++);\r
- keyStore.setCertificateEntry(certificateAlias, certificate);\r
- }\r
-\r
- // Use key store to build an X509 trust manager.\r
- KeyManagerFactory keyManagerFactory =\r
- KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\r
- keyManagerFactory.init(keyStore, DEFAULT_KEYSTORE_PASSWORD);\r
- TrustManagerFactory trustManagerFactory =\r
- TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\r
- trustManagerFactory.init(keyStore);\r
- TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();\r
- if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {\r
- throw new IllegalStateException(\r
- "Unexpected default trust managers:" + Arrays.toString(trustManagers));\r
- }\r
-\r
- this.trustManagers = trustManagers;\r
- return this;\r
- } catch (GeneralSecurityException | IOException ex) {\r
- throw new ConfigurationException("Unable to configure trusted CA certs", ex);\r
- }\r
- }\r
-\r
- /**\r
- * Trusts the given CA certs, and no others. Use this if you are running\r
- * your own CA, or are using a self-signed server certificate.\r
- *\r
- * @param path The path of a file containing certificates to trust, in PEM format.\r
- */\r
- public Builder setTrustedCerts(String path) throws ConfigurationException {\r
- try (InputStream is = new FileInputStream(path)) {\r
- return setTrustedCerts(is);\r
- } catch (IOException ex) {\r
- throw new ConfigurationException("Unable to configure trusted CA certs", ex);\r
- }\r
- }\r
-\r
- /**\r
- * Sets the certificate pinner for the client\r
- *\r
- * @param provider certificate provider\r
- * @param subjPubKeyInfoHash public key hash\r
- */\r
- public Builder pinCertificate(String provider, String subjPubKeyInfoHash) {\r
- this.cp = new CertificatePinner.Builder().add(provider, subjPubKeyInfoHash).build();\r
- return this;\r
- }\r
-\r
- /**\r
- * Sets the connect timeout for the client\r
- *\r
- * @param timeout the number of time units for the default timeout\r
- * @param unit the unit of time\r
- */\r
- public Builder setConnectTimeout(long timeout, TimeUnit unit) {\r
- this.connectTimeout = timeout;\r
- this.connectTimeoutUnit = unit;\r
- return this;\r
- }\r
-\r
- /**\r
- * Sets the read timeout for the client\r
- *\r
- * @param timeout the number of time units for the default timeout\r
- * @param unit the unit of time\r
- */\r
- public Builder setReadTimeout(long timeout, TimeUnit unit) {\r
- this.readTimeout = timeout;\r
- this.readTimeoutUnit = unit;\r
- return this;\r
- }\r
-\r
- /**\r
- * Sets the write timeout for the client\r
- *\r
- * @param timeout the number of time units for the default timeout\r
- * @param unit the unit of time\r
- */\r
- public Builder setWriteTimeout(long timeout, TimeUnit unit) {\r
- this.writeTimeout = timeout;\r
- this.writeTimeoutUnit = unit;\r
- return this;\r
- }\r
-\r
- /**\r
- * Sets the proxy for the client\r
- *\r
- * @param proxy\r
- */\r
- public Builder setProxy(Proxy proxy) {\r
- this.proxy = proxy;\r
- return this;\r
- }\r
-\r
- /**\r
- * Sets the connection pool for the client\r
- *\r
- * @param maxIdle the maximum number of idle http connections in the pool\r
- * @param timeout the number of time units until an idle http connection in the pool is closed\r
- * @param unit the unit of time\r
- */\r
- public Builder setConnectionPool(int maxIdle, long timeout, TimeUnit unit) {\r
- this.pool = new ConnectionPool(maxIdle, unit.toMillis(timeout));\r
- return this;\r
- }\r
-\r
- /**\r
- * Builds a client with all of the provided parameters.\r
- */\r
- public Client build() throws ConfigurationException {\r
- return new Client(this);\r
- }\r
- }\r
-}\r
+++ /dev/null
-package io.bytom.types;\r
-\r
-\r
-import com.google.gson.Gson;\r
-import com.google.gson.GsonBuilder;\r
-import com.google.gson.reflect.TypeToken;\r
-import io.bytom.common.DerivePrivateKey;\r
-import io.bytom.common.DeriveXpub;\r
-import io.bytom.util.SHA3Util;\r
-import org.bouncycastle.util.encoders.Hex;\r
-\r
-import java.io.ByteArrayOutputStream;\r
-import java.security.InvalidKeyException;\r
-import java.security.NoSuchAlgorithmException;\r
-import java.security.SignatureException;\r
-import java.util.LinkedHashMap;\r
-import java.util.Map;\r
-\r
-public class Asset {\r
-\r
- /**\r
- * type : asset\r
- * xpubs : ["135022d3c218e949de69902459ba4233c8a21ecf2fde00ea592876e3138f1bf09dea25de09b0018b35a741d8cd9f6ec06bc11db49762617485f5309ab72a12d4"]\r
- * quorum : 1\r
- * id : 821ab3d068a218e2ec23c28f50786c7f52412394c52bf9f9319d58bd3e459fa3\r
- * alias : TEST7\r
- * definition : {"decimals":8,"description":{},"name":"","symbol":""}\r
- * key_index : 14\r
- * derive_rule : 0\r
- * vm_version : 1\r
- * issue_program : ae202dcda0296db65a471f5e111ed1e61afec158f1ac6be8f8c23c6ccaefa27c5dfa5151ad\r
- * raw_definition_byte : 7b0a202022646563696d616c73223a20382c0a2020226465736372697074696f6e223a207b7d2c0a2020226e616d65223a2022222c0a20202273796d626f6c223a2022220a7d\r
- */\r
-\r
- public String type;\r
- public int quorum;\r
- public String id;\r
- public String alias;\r
- public Definition definition;\r
- public int keyIndex;\r
- public int deriveRule;\r
- public int vmVersion;\r
- public String issueProgram;\r
- public String rawDefinitionByte;\r
- public String xpubs;\r
-\r
- public Asset() {\r
-\r
- }\r
-\r
- public Asset(String rawDefinitionByte, int keyIndex, String rootKey) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {\r
- String issueProgram = computeIssueProgram(rootKey, keyIndex);\r
- String assetID = computeAssetID(issueProgram, 1, rawDefinitionByte);\r
- this.keyIndex = keyIndex;\r
- this.id = assetID;\r
- this.rawDefinitionByte = rawDefinitionByte;\r
- this.issueProgram = issueProgram;\r
- }\r
-\r
- public Asset CreateAsset(Definition definitionp, int keyIndex, String rootKey) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {\r
- String rawDefinitionByte = computeRawDefinition(definitionp);\r
- String issueProgram = computeIssueProgram(rootKey, keyIndex);\r
- String assetID = computeAssetID(issueProgram, 1, rawDefinitionByte);\r
- this.keyIndex = keyIndex;\r
- this.id = assetID;\r
- this.issueProgram = issueProgram;\r
- this.rawDefinitionByte = rawDefinitionByte;\r
- return this;\r
- }\r
-\r
- private String computeIssueProgram(String rootKey, int keyIndex) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {\r
- byte[] derivePrivateKey = DerivePrivateKey.bip32derivePrvKey(rootKey, keyIndex, (byte) 0, 1);\r
- byte[] deriveXpub = DeriveXpub.deriveXpub(derivePrivateKey);\r
-\r
- String issueProgram = "ae20" + Hex.toHexString(deriveXpub).substring(0, 64) + "5151ad";\r
- return issueProgram;\r
- }\r
-\r
- private String computeAssetID(String issuanceProgram, int VMVersion, String rawDefinitionByte) {\r
- byte[] rawDefinitionBytes = SHA3Util.hashSha256(Hex.decode(rawDefinitionByte));\r
- Hash assetDefineHash = new Hash(rawDefinitionBytes);\r
- Program pro = new Program(1, Hex.decode(issuanceProgram));\r
- AssetDefinition assetDefinition = new AssetDefinition(assetDefineHash, pro);\r
- ByteArrayOutputStream bo = new ByteArrayOutputStream();\r
- assetDefinition.writeForHash(bo);\r
- byte[] assetIDBytes = SHA3Util.hashSha256(bo.toByteArray());\r
- String assetID = Hex.toHexString(assetIDBytes);\r
- return assetID;\r
- }\r
-\r
- private String computeRawDefinition(final Definition definition) {\r
- Map<String, Object> map = new LinkedHashMap<String, Object>() {\r
- {\r
- put("decimals", definition.getDecimals());\r
- put("description", definition.getDescription());\r
- put("name", definition.getName());\r
- put("symbol", definition.getSymbol());\r
- }\r
- };\r
- Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
- String json = gson.toJson(map, new TypeToken<Map<String, Object>>() {\r
- }.getType());\r
- String rawDefinition = Hex.toHexString(json.getBytes());\r
- return rawDefinition;\r
- }\r
-\r
-\r
- public static class Definition {\r
- private int decimals;\r
- private Object description;\r
- private String name;\r
- private String symbol;\r
-\r
- public int getDecimals() {\r
- return decimals;\r
- }\r
-\r
- public void setDecimals(int decimals) {\r
- this.decimals = decimals;\r
- }\r
-\r
- public Object getDescription() {\r
- return description;\r
- }\r
-\r
- public void setDescription(Object description) {\r
- this.description = description;\r
- }\r
-\r
- public String getName() {\r
- return name;\r
- }\r
-\r
- public void setName(String name) {\r
- this.name = name;\r
- }\r
-\r
- public String getSymbol() {\r
- return symbol;\r
- }\r
-\r
- public void setSymbol(String symbol) {\r
- this.symbol = symbol;\r
- }\r
- }\r
-\r
-}\r
\r
public class AssetAmount {\r
\r
- public AssetID assetID;\r
+ private AssetID assetID;\r
\r
- public long amount;\r
+ private Long amount;\r
\r
- public AssetAmount() {\r
- }\r
+ public AssetAmount() {}\r
\r
public AssetAmount(AssetID assetID, long amount) {\r
this.assetID = assetID;\r
this.amount = amount;\r
}\r
+\r
+ public AssetID getAssetID() {\r
+ return assetID;\r
+ }\r
+\r
+ public void setAssetID(AssetID assetID) {\r
+ this.assetID = assetID;\r
+ }\r
+\r
+ public Long getAmount() {\r
+ return amount;\r
+ }\r
+\r
+ public void setAmount(Long amount) {\r
+ this.amount = amount;\r
+ }\r
}\r
import java.io.ByteArrayOutputStream;\r
\r
public class AssetDefinition extends Entry {\r
- public Hash assetDefHash;\r
- public Program program;\r
+\r
+ private Hash assetDefHash;\r
+ private Program program;\r
\r
public AssetDefinition(Hash assetDefHash, Program program) {\r
this.assetDefHash = assetDefHash;\r
mustWriteForHash(out, this.program);\r
mustWriteForHash(out, this.assetDefHash);\r
}\r
+\r
+ public Hash getAssetDefHash() {\r
+ return assetDefHash;\r
+ }\r
+\r
+ public Program getProgram() {\r
+ return program;\r
+ }\r
+\r
+ public void setAssetDefHash(Hash assetDefHash) {\r
+ this.assetDefHash = assetDefHash;\r
+ }\r
+\r
+ public void setProgram(Program program) {\r
+ this.program = program;\r
+ }\r
}\r
\r
private String hexValue;\r
\r
- public AssetID() {\r
- }\r
+ public AssetID() {}\r
\r
public AssetID(String hexValue) {\r
this.hexValue = hexValue;\r
package io.bytom.types;\r
\r
+import io.bytom.exception.WriteForHashException;\r
import io.bytom.util.OutputUtil;\r
import org.bouncycastle.jcajce.provider.digest.SHA3;\r
-import org.bouncycastle.util.encoders.Hex;\r
-\r
+import java.beans.PropertyDescriptor;\r
import java.io.ByteArrayOutputStream;\r
import java.io.IOException;\r
import java.lang.reflect.Field;\r
+import java.lang.reflect.Method;\r
\r
public abstract class Entry {\r
\r
public void mustWriteForHash(ByteArrayOutputStream out, Object data) {\r
try {\r
if (data == null) {\r
- return;\r
+ throw new WriteForHashException("The field needs to be written to hash is null");\r
}\r
if (data instanceof Byte) {\r
OutputUtil.writeByte(out, (byte) data);\r
}\r
} else {\r
Class<?> cls = data.getClass();\r
- Field[] fields = cls.getFields();\r
+ Field[] fields = cls.getDeclaredFields();\r
for (Field field : fields) {\r
- mustWriteForHash(out, field.get(data));\r
+ PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), cls);\r
+ Method readMethod = descriptor.getReadMethod();\r
+ mustWriteForHash(out, readMethod.invoke(data));\r
}\r
}\r
} catch (Exception e) {\r
- throw new RuntimeException(e);\r
+ e.printStackTrace();\r
+ throw new WriteForHashException(e);\r
}\r
}\r
\r
hasher.write(digest256.digest(bh.toByteArray()));\r
return new Hash(digest256.digest(hasher.toByteArray()));\r
} catch (IOException e) {\r
+ e.printStackTrace();\r
throw new RuntimeException(e);\r
} finally {\r
try {\r
\r
private String hexValue;\r
\r
- public Hash() {\r
- }\r
+ public Hash() {}\r
\r
public Hash(String hexValue) {\r
this.hexValue = hexValue;\r
public abstract class InputEntry extends Entry {
- public int ordinal;
+ protected int ordinal;
public abstract void setDestination(Hash id, long pos, Map<Hash, Entry> entryMap);
+
+ public int getOrdinal() {
+ return ordinal;
+ }
+
+ public void setOrdinal(int ordinal) {
+ this.ordinal = ordinal;
+ }
}
import java.util.Map;\r
\r
public class Issue extends InputEntry {\r
- public Hash nonceHash;\r
- public AssetAmount assetAmount;\r
- public AssetDefinition assetDefinition;\r
- public ValueDestination witnessDestination;\r
\r
- public Issue(Hash nonceHash, AssetAmount assetAmount, int ordinal) {\r
+ private Hash nonceHash;\r
+ private AssetAmount assetAmount;\r
+ private AssetDefinition assetDefinition;\r
+ private ValueDestination witnessDestination;\r
+\r
+ public Issue(Hash nonceHash, AssetAmount assetAmount, int ordinal, AssetDefinition assetDefinition) {\r
this.nonceHash = nonceHash;\r
this.assetAmount = assetAmount;\r
this.ordinal = ordinal;\r
+ this.assetDefinition = assetDefinition;\r
}\r
\r
@Override\r
mustWriteForHash(out, this.nonceHash);\r
mustWriteForHash(out, this.assetAmount);\r
}\r
+\r
+ public Hash getNonceHash() {\r
+ return nonceHash;\r
+ }\r
+\r
+ public void setNonceHash(Hash nonceHash) {\r
+ this.nonceHash = nonceHash;\r
+ }\r
+\r
+ public AssetAmount getAssetAmount() {\r
+ return assetAmount;\r
+ }\r
+\r
+ public void setAssetAmount(AssetAmount assetAmount) {\r
+ this.assetAmount = assetAmount;\r
+ }\r
+\r
+ public AssetDefinition getAssetDefinition() {\r
+ return assetDefinition;\r
+ }\r
+\r
+ public void setAssetDefinition(AssetDefinition assetDefinition) {\r
+ this.assetDefinition = assetDefinition;\r
+ }\r
+\r
+ public ValueDestination getWitnessDestination() {\r
+ return witnessDestination;\r
+ }\r
+\r
+ public void setWitnessDestination(ValueDestination witnessDestination) {\r
+ this.witnessDestination = witnessDestination;\r
+ }\r
}\r
\r
public class Mux extends Entry {\r
\r
- public ValueSource[] sources;\r
+ private ValueSource[] sources;\r
\r
- public Program program;\r
+ private Program program;\r
\r
- public List<ValueDestination> witnessDestinations = new ArrayList<>();\r
+ private List<ValueDestination> witnessDestinations = new ArrayList<>();\r
\r
- public Mux() {\r
- }\r
+ public Mux() {}\r
\r
public Mux(ValueSource[] sources, Program program) {\r
- this();\r
this.sources = sources;\r
this.program = program;\r
}\r
mustWriteForHash(out, this.sources);\r
mustWriteForHash(out, this.program);\r
}\r
+\r
+ public ValueSource[] getSources() {\r
+ return sources;\r
+ }\r
+\r
+ public void setSources(ValueSource[] sources) {\r
+ this.sources = sources;\r
+ }\r
+\r
+ public Program getProgram() {\r
+ return program;\r
+ }\r
+\r
+ public void setProgram(Program program) {\r
+ this.program = program;\r
+ }\r
+\r
+ public List<ValueDestination> getWitnessDestinations() {\r
+ return witnessDestinations;\r
+ }\r
+\r
+ public void setWitnessDestinations(List<ValueDestination> witnessDestinations) {\r
+ this.witnessDestinations = witnessDestinations;\r
+ }\r
}\r
\r
public class OutputEntry extends Entry {\r
\r
- public ValueSource source;\r
+ private ValueSource source;\r
\r
- public Program controlProgram;\r
+ private Program controlProgram;\r
\r
- public Integer ordinal;\r
+ private Integer ordinal;\r
\r
public OutputEntry() {\r
this.source = new ValueSource();\r
mustWriteForHash(out, this.source);\r
mustWriteForHash(out, this.controlProgram);\r
}\r
+\r
+ public ValueSource getSource() {\r
+ return source;\r
+ }\r
+\r
+ public void setSource(ValueSource source) {\r
+ this.source = source;\r
+ }\r
+\r
+ public Program getControlProgram() {\r
+ return controlProgram;\r
+ }\r
+\r
+ public void setControlProgram(Program controlProgram) {\r
+ this.controlProgram = controlProgram;\r
+ }\r
+\r
+ public Integer getOrdinal() {\r
+ return ordinal;\r
+ }\r
+\r
+ public void setOrdinal(Integer ordinal) {\r
+ this.ordinal = ordinal;\r
+ }\r
}\r
\r
public class Program {\r
\r
- public long vmVersion;\r
+ private long vmVersion;\r
\r
- public byte[] code;\r
+ private byte[] code;\r
\r
- public Program() {\r
- }\r
+ public Program() {}\r
\r
public Program(long vmVersion, byte[] code) {\r
this.vmVersion = vmVersion;\r
this.code = code;\r
}\r
+\r
+ public long getVmVersion() {\r
+ return vmVersion;\r
+ }\r
+\r
+ public void setVmVersion(long vmVersion) {\r
+ this.vmVersion = vmVersion;\r
+ }\r
+\r
+ public byte[] getCode() {\r
+ return code;\r
+ }\r
+\r
+ public void setCode(byte[] code) {\r
+ this.code = code;\r
+ }\r
}\r
import java.io.ByteArrayOutputStream;\r
\r
public class Retirement extends Entry {\r
- public ValueSource valueSource;\r
- public int ordinal;\r
+\r
+ private ValueSource valueSource;\r
+ private int ordinal;\r
\r
public Retirement(ValueSource valueSource, int ordinal) {\r
this.valueSource = valueSource;\r
public void writeForHash(ByteArrayOutputStream out) {\r
mustWriteForHash(out, valueSource);\r
}\r
+\r
+ public ValueSource getValueSource() {\r
+ return valueSource;\r
+ }\r
+\r
+ public void setValueSource(ValueSource valueSource) {\r
+ this.valueSource = valueSource;\r
+ }\r
+\r
+ public int getOrdinal() {\r
+ return ordinal;\r
+ }\r
+\r
+ public void setOrdinal(int ordinal) {\r
+ this.ordinal = ordinal;\r
+ }\r
}\r
\r
public class Spend extends InputEntry {\r
\r
- public Hash spentOutputID;\r
+ private Hash spentOutputID;\r
\r
- public int ordinal;\r
+ private int ordinal;\r
\r
- public ValueDestination witnessDestination;\r
+ private ValueDestination witnessDestination;\r
\r
- public byte[][] witnessArguments;\r
+ private byte[][] witnessArguments;\r
\r
public Spend(Hash spentOutputID, int ordinal) {\r
this.spentOutputID = spentOutputID;\r
@Override\r
public void setDestination(Hash id, long pos, Map<Hash, Entry> entryMap) {\r
OutputEntry spendOutput = (OutputEntry) entryMap.get(this.spentOutputID);\r
- this.witnessDestination = new ValueDestination(id, spendOutput.source.value, pos);\r
+ this.witnessDestination = new ValueDestination(id, spendOutput.getSource().getValue(), pos);\r
}\r
\r
@Override\r
public void writeForHash(ByteArrayOutputStream out) {\r
mustWriteForHash(out, this.spentOutputID);\r
}\r
+\r
+ public Hash getSpentOutputID() {\r
+ return spentOutputID;\r
+ }\r
+\r
+ public void setSpentOutputID(Hash spentOutputID) {\r
+ this.spentOutputID = spentOutputID;\r
+ }\r
+\r
+ @Override\r
+ public int getOrdinal() {\r
+ return ordinal;\r
+ }\r
+\r
+ @Override\r
+ public void setOrdinal(int ordinal) {\r
+ this.ordinal = ordinal;\r
+ }\r
+\r
+ public ValueDestination getWitnessDestination() {\r
+ return witnessDestination;\r
+ }\r
+\r
+ public void setWitnessDestination(ValueDestination witnessDestination) {\r
+ this.witnessDestination = witnessDestination;\r
+ }\r
+\r
+ public byte[][] getWitnessArguments() {\r
+ return witnessArguments;\r
+ }\r
+\r
+ public void setWitnessArguments(byte[][] witnessArguments) {\r
+ this.witnessArguments = witnessArguments;\r
+ }\r
}\r
\r
public class TxHeader extends Entry {\r
\r
- public long version;\r
+ private long version;\r
\r
- public long serializedSize;\r
+ private long serializedSize;\r
\r
- public long timeRange;\r
+ private long timeRange;\r
\r
- public Hash[] resultIDs;\r
+ private Hash[] resultIDs;\r
\r
- public TxHeader() {\r
- }\r
+ public TxHeader() {}\r
\r
public TxHeader(long version, long serializedSize, long timeRange, Hash[] resultIDs) {\r
this.version = version;\r
mustWriteForHash(out, this.timeRange);\r
mustWriteForHash(out, this.resultIDs);\r
}\r
+\r
+ public long getVersion() {\r
+ return version;\r
+ }\r
+\r
+ public void setVersion(long version) {\r
+ this.version = version;\r
+ }\r
+\r
+ public long getSerializedSize() {\r
+ return serializedSize;\r
+ }\r
+\r
+ public void setSerializedSize(long serializedSize) {\r
+ this.serializedSize = serializedSize;\r
+ }\r
+\r
+ public long getTimeRange() {\r
+ return timeRange;\r
+ }\r
+\r
+ public void setTimeRange(long timeRange) {\r
+ this.timeRange = timeRange;\r
+ }\r
+\r
+ public Hash[] getResultIDs() {\r
+ return resultIDs;\r
+ }\r
+\r
+ public void setResultIDs(Hash[] resultIDs) {\r
+ this.resultIDs = resultIDs;\r
+ }\r
}\r
\r
public class ValueDestination {\r
\r
- public Hash ref;\r
+ private Hash ref;\r
\r
- public AssetAmount value;\r
+ private AssetAmount value;\r
\r
- public long position;\r
+ private long position;\r
\r
- public ValueDestination() {\r
- }\r
+ public ValueDestination() {}\r
\r
public ValueDestination(Hash ref, AssetAmount value, long position) {\r
this.ref = ref;\r
this.value = value;\r
this.position = position;\r
}\r
+\r
+ public Hash getRef() {\r
+ return ref;\r
+ }\r
+\r
+ public void setRef(Hash ref) {\r
+ this.ref = ref;\r
+ }\r
+\r
+ public AssetAmount getValue() {\r
+ return value;\r
+ }\r
+\r
+ public void setValue(AssetAmount value) {\r
+ this.value = value;\r
+ }\r
+\r
+ public long getPosition() {\r
+ return position;\r
+ }\r
+\r
+ public void setPosition(long position) {\r
+ this.position = position;\r
+ }\r
}\r
\r
public class ValueSource {\r
\r
- public Hash ref;\r
+ private Hash ref;\r
\r
- public AssetAmount value;\r
+ private AssetAmount value;\r
\r
- public long position;\r
+ private long position;\r
\r
- public ValueSource() {\r
- }\r
+ public ValueSource() {}\r
\r
public ValueSource(Hash ref, AssetAmount value, long position) {\r
this.ref = ref;\r
this.position = position;\r
}\r
\r
+ public Hash getRef() {\r
+ return ref;\r
+ }\r
+\r
+ public void setRef(Hash ref) {\r
+ this.ref = ref;\r
+ }\r
+\r
+ public AssetAmount getValue() {\r
+ return value;\r
+ }\r
+\r
+ public void setValue(AssetAmount value) {\r
+ this.value = value;\r
+ }\r
+\r
+ public long getPosition() {\r
+ return position;\r
+ }\r
+\r
+ public void setPosition(long position) {\r
+ this.position = position;\r
+ }\r
}\r
+++ /dev/null
-package io.bytom;\r
-\r
-import io.bytom.common.Configuration;\r
-import io.bytom.exception.BytomException;\r
-import io.bytom.http.Client;\r
-import org.apache.log4j.Logger;\r
-\r
-public class TestUtil {\r
- public static Logger logger = Logger.getLogger(TestUtil.class);\r
-\r
- public static Client generateClient() throws BytomException {\r
-\r
- String coreURL = Configuration.getValue("bytom.api.url");\r
- String accessToken = Configuration.getValue("client.access.token");\r
-\r
- if (coreURL == null || coreURL.isEmpty()) {\r
- coreURL = "http://127.0.0.1:9888";\r
- }\r
-\r
- if (coreURL.endsWith("/")) {\r
- //split the last char "/"\r
- coreURL = coreURL.substring(0, coreURL.length() - 1);\r
- }\r
-\r
- return new Client(coreURL, accessToken);\r
- }\r
-}\r
out.reset();\r
ValueSource valueSource = new ValueSource(new Hash(hash), null, 1);\r
Program program = new Program(1, new byte[]{1});\r
- Mux mux = new Mux();\r
- mux.sources = new ValueSource[]{valueSource};\r
- mux.program = program;\r
+ Mux mux = new Mux(new ValueSource[]{valueSource}, program);\r
entry.mustWriteForHash(out, mux);\r
assert Hex.toHexString(out.toByteArray()).equals("01d8ab56a5c9296f591db071a8b63f395e1485b12d4b105b49fee287c03888331f010000000000000001000000000000000101");\r
}\r
String hash = "d8ab56a5c9296f591db071a8b63f395e1485b12d4b105b49fee287c03888331f";\r
ValueSource valueSource = new ValueSource(new Hash(hash), null, 1);\r
Program program = new Program(1, new byte[]{1});\r
- Mux mux = new Mux();\r
- mux.sources = new ValueSource[]{valueSource};\r
- mux.program = program;\r
+ Mux mux = new Mux(new ValueSource[]{valueSource}, program);\r
String entryID = mux.entryID().toString();\r
assert entryID.equals("ebd967df33a3373ab85521fba24c22bf993c73f46fa96254b0c86646093184e9");\r
}\r
+++ /dev/null
-package io.bytom.types;\r
-\r
-import com.google.gson.Gson;\r
-import org.junit.Test;\r
-\r
-import java.security.InvalidKeyException;\r
-import java.security.NoSuchAlgorithmException;\r
-import java.security.SignatureException;\r
-\r
-public class AssetTest {\r
- String rootkey = "38d2c44314c401b3ea7c23c54e12c36a527aee46a7f26b82443a46bf40583e439dea25de09b0018b35a741d8cd9f6ec06bc11db49762617485f5309ab72a12d4";\r
-\r
- @Test\r
- public void testCreateAsset() throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {\r
- Object o = new Object();\r
- Asset.Definition definition = new Asset.Definition();\r
-\r
-// "definition": {\r
-// "decimals": 8,\r
-// "description": "Bytom Official Issue",\r
-// "name": "BTM",\r
-// "symbol": "BTM"\r
-// }\r
- definition.setDecimals(8);\r
- //{}\r
- definition.setDescription(o);\r
- definition.setName("");\r
- definition.setSymbol("");\r
-\r
- Asset asset = new Asset();\r
- asset.CreateAsset(definition, 2, rootkey);\r
- Gson gson = new Gson();\r
- String s = gson.toJson(asset);\r
- System.out.println(s);\r
- }\r
-}\r