Code Monkey home page Code Monkey logo

iota-java's Introduction


The official Java client library for interacting with the legacy Tangle (deprecated since Chrysalis)

Developer documentation portal

Auto-generated docs Discord StackExchange Apache 2.0 license Supported IRI API endpoints Code quality Latest release Build status

AboutPrerequisitesInstallationGetting startedAPI referenceExamplesChange logsSupporting the projectJoining the discussion


Deprecation warning

This java client is no longer usable in the new Chrysalis network. Please use the Java bindings generated for iota.rs. They can be found here

About

This was the official Java client library, which allows you to do the following:

  • Create transactions
  • Read transactions
  • Sign transactions
  • Generate addresses

This is beta software, so there may be performance and stability issues. Please report any issues in our issue tracker.

Prerequisites

To use the IOTA Java client library, your computer must have the following minimum requirement:

  • Java 6 (or higher)

Installation

The IOTA Java client library is available on [jitpack.io][jitpack].

To install the IOTA Java client library and its dependencies, you can use one of the following options:

  • Download the library with Gradle
  • Download the library with Maven
  • Download the library manually

Gradle

  1. Add the following repository to your root build.gradle file (not your module build.gradle file):

    allprojects {
        repositories {
            maven { url 'https://jitpack.io' }
        }
    }
  2. Add the following dependency to your module build.gradle file:

    dependencies {
        compile 'com.github.iotaledger:iota-java:1.0.0-beta8'
    }

Maven

Through Maven central

  1. Add the following repository to your root pom.xml file:
    <dependency>
        <groupId>org.iota</groupId>
        <artifactId>jota</artifactId>
        <classifier>jar-with-dependencies</classifier>
        <version>1.0.0-beta9</version>
    </dependency>

Through Jitpack

  1. Add the following repository to your root pom.xml file:

    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>
  2. Add the following dependency to your module pom.xml file:

    <dependency>
        <groupId>com.github.iotaledger.iota-java</groupId>
        <artifactId>jota</artifactId>
        <classifier>jar-with-dependencies</classifier>
        <version>[VERSION_INFORMATION]</version>
    </dependency>
  3. Change the value of the <version> tag to either a release number or the first 10 characters of a Git commit hash: <version>b703ef3c05f05</version> or <version>1.0.0-beta9</version>

Note: Find the latest version on the Jitpack page.

Manual installation

  1. Clone or download the GitHub repository.

    Inside the project, you'll have the following directories:

    • jota
    • jota-parent
  2. Import and reference the jota directory in your project For example in Eclipse: right mouse on your project -> Properties -> Java Build Path -> Projects -> Add 'jota'

  3. In the jota directory, run the following command:

    mvn clean install

You'll have a .jar file called jota-[VERSION]-jar-with-dependencies.jar, depending on your version of the library.

Getting Started

After you've installed the library, you can connect to an IRI node to send transactions to it and interact with the Tangle. An extended guide can be found on our documentation portal, we strongly recommend you to go here for starting off. A quick start tutorial is shown below.

To connect to a local IRI node on port 14265, do the following:

IotaAPI api = new IotaAPI.Builder().build();
GetNodeInfoResponse response = api.getNodeInfo();

To connect to a remote IRI node on port 14265, do the following:

IotaAPI api = new IotaAPI.Builder()
        .protocol("http")
        .host("URL OF THE REMOTE IRI NODE")
        .port(14265)
        .build();
GetNodeInfoResponse response = api.getNodeInfo();

Note: To separate your IRI node configuration from the implementation, you can also specify your IRI node configuration in a Java .properties file or as command line flags. These options are useful if you develop an open-source app which is deployed on a CI and don't want contributors to see the internal IRI node configuration. To make the API read from this file, add the configuration to the builder like so: .config(new FileConfig("node_config.properties"))

Example .properties files

iota.node.protocol=http
iota.node.host=127.0.0.1
iota.node.port=14265

Most API calls are synchronous. Therefore, we recommend that you call the API from a background thread or a worker thread to stop the API from blocking other threads such as the UI or the main thread.

API Reference

For a full list of API commands for the IOTA Java client library, go to the GitHub page.

Here are some of the most commonly used API functions:

Examples

We have a list of test cases in the src/test/java directory that you can use as a reference when developing apps with IOTA. A good starter is the IotaAPITest case.

Here's how you could send a zero-value transaction, using the library. For the guide, see the documentation portal.

class SendData {
    public static void main(String[] args) throws ArgumentException {

        // Connect to a node
        IotaAPI api = new IotaAPI.Builder()
            .protocol("https")
            .host("nodes.devnet.thetangle.org")
            .port(443)
            .build();

        int depth = 3;
        int minimumWeightMagnitude = 9;

        // Even though a seed is not necessary because zero value transactions are not signed,
        // the library requires a seed to send a transaction.
        // This seed can be any random string of 81 trytes
        String myRandomSeed = SeedRandomGenerator.generateNewSeed();

        // Define any security level (like the seed, this is not used)
        int securityLevel = 2;

        // Define an address.
        // This does not need to belong to anyone or have IOTA tokens.
        // It must only contain a maximum of 81 trytes
        // or 90 trytes with a valid checksum
        String address = "ZLGVEQ9JUZZWCZXLWVNTHBDX9G9KZTJP9VEERIIFHY9SIQKYBVAHIMLHXPQVE9IXFDDXNHQINXJDRPFDXNYVAPLZAW";
        // This is a zero-value transaction
        int value = 0;
        // Define a message to send.
        // This message must include only ASCII characters.
        String message = TrytesConverter.asciiToTrytes("Hello world");
        String tag = "HELLOWORLD";

        Transfer zeroValueTransaction = new Transfer(address, value, message, tag);
        
        ArrayList<Transfer> transfers = new ArrayList<Transfer>();

        transfers.add(zeroValueTransaction);
        
        // Create a bundle from the transfers list
        // and send the transaction to the node
        try { 
            // Since we don't send any value, we can skip validation of inputs
            SendTransferResponse response = api.sendTransfer(myRandomSeed, securityLevel, depth, minimumWeightMagnitude, transfers, null, null, false, false, null);
            System.out.println(response.getTransactions());
        } catch (ArgumentException e) { 
            // Handle error
            e.printStackTrace(); 
         }
    }
}

Change logs

Supporting the project

If the IOTA Java client library has been useful to you and you feel like contributing, consider posting a bug report, feature request or a pull request.

We have some basic contribution guidelines to keep our code base stable and consistent.

Joining the discussion

If you want to get involved in the community, need help with getting setup, have any issues related with the library or just want to discuss blockchain, distributed ledgers, and IoT with other people, feel free to join our Discord.

iota-java's People

Contributors

adrianziser avatar alexkarezin avatar bartoszmiller avatar d35h avatar davassi avatar ezienecker avatar france193 avatar githubdevcode avatar gosticks avatar iauglov avatar jakescahill avatar janheinrichmerker avatar jcminarro avatar jpkrohling avatar kwek20 avatar paulhandy avatar pcwu avatar pinpong avatar schierlm avatar th0br0 avatar thoralf-m avatar toonsevrin avatar vgrankin1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

iota-java's Issues

support the `reference` param in `getTransactionsToApprove`

the API call getTransactionsToApprove has a reference parameter that allows a user to specify a transaction that will be referenced by transactions.

this is useful for promoting a specific transaction and to create a conditional chain of spends.

Subjection about IotaAPI.getNewAddress() method

  1. The method name is get "New" address,but actually is not.(index maybe reused)

  2. Another confuse is that if I want to get 2 new address, I will never get it by this method.
    See below when get first new address(no any transaction in there) will break.that cause always get the same new address.

        // No total provided: Continue calling findTransactions to see if address was
        // already created if null, return list of addresses
        for (int i = index; ; i++) {

            final String newAddress = IotaAPIUtils.newAddress(seed, security, i, checksum, customCurl.clone());
            final FindTransactionResponse response = findTransactionsByAddresses(newAddress);

            allAddresses.add(newAddress);
            if (response.getHashes().length == 0) {
                break;
            }
        }

Wrong trunk and branch setting in bundle

I compared JOTA's attachToTangle routine with the IRI implementation [attachToTangleStatement] and I noticed a discrepancy:

When doing local PoW in JOTA the trunk and branch are set differently (compared to the one in IRI) since the loop runs exactly the other way around. So the way a tx attaches to tips produces different result.

I am not sure but maybe this difference in bundle-structure can lead to problems in other parts of the code (which implicitly assume a certain structure).

JOTA IotaAPICore.java:

  for (int i = 0; i < trytes.length; i++) {
                Transaction txn = new Transaction(trytes[i]);
                txn.setTrunkTransaction(previousTransaction == null ? trunkTransaction : previousTransaction);
                txn.setBranchTransaction(previousTransaction == null ? branchTransaction : trunkTransaction);
                .....
                previousTransaction = new Transaction(resultTrytes[i]).getHash();
}

IRI API.java:

 for (final String tryte : trytes) {
                ......
                //branch and trunk
                System.arraycopy((prevTransaction == null ? trunkTransaction : prevTransaction).trits(), 0,
                        transactionTrits, TransactionViewModel.TRUNK_TRANSACTION_TRINARY_OFFSET,
                        TransactionViewModel.TRUNK_TRANSACTION_TRINARY_SIZE);
                System.arraycopy((prevTransaction == null ? branchTransaction : trunkTransaction).trits(), 0,
                        transactionTrits, TransactionViewModel.BRANCH_TRANSACTION_TRINARY_OFFSET,TransactionViewModel.BRANCH_TRANSACTION_TRINARY_SIZE);
                 .....
}
for (int i = transactionViewModels.size(); i-- > 0; ) {
            elements.add(Converter.trytes(transactionViewModels.get(i).trits()));
}

IotaAPI#getBalanceAndFormat bad method

  1. KeyIndex abuse
    Let's say we provide two addresses as input:
    One has an index of 5, the other as 10.

Our getBalanceAndFormat query would look like:
getBalanceAndFormat(addresses, threshold, 5, 0, new StopWatch(), 2)

Due to the implementation for getBalanceAndFormat the returned inputs will have as keyindices 5 and 6.

  1. The end parameter is unused (and not necessary)

solution
Instead of having a List addresses as a param, use a Map<String, Integer> indexByAddress or something, or a custom object.

Can not send a transaction

I used iota java library jota-0.9.10-SNAPSHOT.jar, and connected to IRI node

Full NOde infor:

jota.dto.response.GetNodeInfoResponse@55b699ef[
  appName=IRI
  appVersion=1.4.1.2
  jreVersion=1.8.0_131
  jreAvailableProcessors=8
  jreFreeMemory=163106168
  jreMaxMemory=7430733824
  jreTotalMemory=2780299264
  latestMilestone=WMCQQAZZBZZOLMXOXEVLB9RSUMPPUXCRXHNNCFIFZIHQHORFRLZXSPROQVLPEUBAYUFYMBTMDLRZ99999
  latestMilestoneIndex=285283
  latestSolidSubtangleMilestone=WMCQQAZZBZZOLMXOXEVLB9RSUMPPUXCRXHNNCFIFZIHQHORFRLZXSPROQVLPEUBAYUFYMBTMDLRZ99999
  latestSolidSubtangleMilestoneIndex=285283
  neighbors=11
  packetsQueueSize=0
  time=1511150565324
  tips=8413
  transactionsToRequest=1
  duration=0
]
  IotaAPI api = new IotaAPI.Builder()
                .protocol("http")
                .host("service.iotasupport.com")
                .port("14265")
                .build();

        String seed = "MY_SEED";
        String tag2 = "UPDATE999999999999999999999";
        String sendToAddress = "NYYVQVJMQVYCB9AQXTYFQOZP99R9GRIYRJV9MYIJKTBNXRMAGDXJQWYFKCXBPRLRPBZRRHRZOZTFEWJXBIRWEEGCTW";
        List<Transfer> transfers = new ArrayList<>();
        transfers.add(new jota.model.Transfer(sendToAddress, 0, "ATTACH", tag2));
        SendTransferResponse str = api.sendTransfer(seed, 2, 5, 14, transfers, null, null, false);
        System.out.println(Arrays.toString(str.getSuccessfully()));

I got this error message, any one can help

java.lang.IllegalAccessError: 401 {"error":"COMMAND attachToTangle is not available on this node","duration":0}

api.getAccountData produces warning and return 0 balance.

I'm using testnet for PoC. I tried to get account data for my seed by using api.getAccountData, unfortunately it produces warning and return no balance and no transfers. In the log I found the following warning:

19:30:00.810 [Parallel.For-0] WARN jota.IotaAPI - GetBundleError: 
jota.error.InvalidSignatureException: [Invalid Signatures!]
    at jota.IotaAPI.getBundle(IotaAPI.java:703)
    at jota.IotaAPI$1.perform(IotaAPI.java:198)
    at jota.IotaAPI$1.perform(IotaAPI.java:194)
    at jota.utils.Parallel$1.call(Parallel.java:44)
    at jota.utils.Parallel$1.call(Parallel.java:41)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

It was called as follows:

 final GetAccountDataResponse accountData = api1.getAccountData(seed1, 1,0,true,0,true,0,0,true,0);

The same JS call works like a charm:

iota1.api.getAccountData(seed1, function(e, accountData){
    if (e) {
        console.log('Can\'t get balance for seed1 ', e);
    } else {
        console.log('Balanse for seed1 is: \n', accountData);
    }
});

and returns more adequate results:

{ latestAddress: 'NCBCUUKBMVOEKPEMLYWZDNGQVUIA9CLNJXPASMZXKSJIYYNLAVPZJIWMITBOHDXQSEHKZUITNVOMDQAJW',
  addresses: 
   [ 'XDLWWFWQUE9GBAAK9VCIYDLXPEHUHKQAPMSGML9GCDMTXFGBPXFYKCGTVVBF9JB9EQVBOXJFVEDQKUFGZ',
     'SGQBRPBYBUNCFD9ZCFMPGIRHLMXNZTKDPXYVDHKPRMZ9JE9G9XKSFHPEK9UENJRAZKOZPUIQ9CDA9AHYW',
     'SNNZ9RIZMQONXJARXUABJPZCFSJXXEYVPI9QPI9EXQVYYQTNALMUHUDIESBG9SLLWBXGL9LIAYEFAJIDA' ],
  transfers: 
   [ [ [Object], [Object], [Object], [Object] ],
     [ [Object] ],
     [ [Object], [Object], [Object], [Object] ] ],
  inputs: 
   [ { address: 'XDLWWFWQUE9GBAAK9VCIYDLXPEHUHKQAPMSGML9GCDMTXFGBPXFYKCGTVVBF9JB9EQVBOXJFVEDQKUFGZ',
       keyIndex: 0,
       security: 2,
       balance: 1000000000 } ],
  balance: 1000000000 }

I also checked api.getTransfers for both languages and found that the results are the same.

I'm not sure whether this warning valid or not, and why it works on JS and fails on Java, but, definitely. if it affects the returning results it should be propagated rather than being swallowed.

Do not shade the dependencies into the JAR

Shading the dependencies might be useful for end user applications, but should be avoided for libraries. The current problem I'm facing is that I can't disable slf4j from the library, because including the slf4j-nop dependency yields this:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/mnt/storage/jpkroehling/Tools/m2-repository/repository/org/iota/jota/0.9.1/jota-0.9.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/.../.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-nop/1.6.4/e576e513871997285f171d1c8b695185bd9c86cc/slf4j-nop-1.6.4.jar!/org/slf4j/impl/StaticLoggerBinder.class]

Release to Maven central

As soon as there is an official release, we want to be able to use the library directly from maven without third party repositories.

Connecting to testnet

Hi,

I apologize in advance for this question if it's been asked before. I could not find the documentation.

How would the API start-up sequence change if I wanted to connect to the IOTA test network (Mainnet)?

Thank you,

Alex Donnini

IllegalAccessError when calling findTransactionsByBundles

I'm not sure how to reproduce this error, but I keep finding it in my server logs before iotasear.ch crashes. Any ideas?

java.lang.IllegalAccessError: 400
	at jota.IotaAPICore.wrapCheckedException(IotaAPICore.java:73)
	at jota.IotaAPICore.findTransactions(IotaAPICore.java:176)
	at jota.IotaAPICore.findTransactionsByBundles(IotaAPICore.java:184)

Can't get library installed

I am getting the error "Missing artifact". Marven-wrapper jar is in place. However, where is the "build file"?

I am using Eclipse and a Maven project

sendTransfer does not sign correctly from addresses with sec-level 3

Running this code in node -> iota.api.getNewAddress(seed ,{'index':0,'checksum':false,'total':1,'security':3}, function(e, s) { console.log(s) } )
gave me an address SRIVO9VGLUWGHFMXAFUFQRTWPTZWN9PJ9Y9AFDUFQNXMEPJYPFEPKNGBPNWYTOHSWWCWKGNFMWNGDDPPWOGAWZKMDC
This is a sec-level 3 address.
I sendt 100 i to that address. After confirmation I used the Java-lib to send from that address, but the transaction that was made is invalid.

	IotaAPI proxy = new IotaAPI.Builder().build();
	GetBalancesAndFormatResponse rsp = proxy.getInputs(seed, 3, 0, 6, 100);
	System.out.println(rsp.toString());
	Transfer transfer = new Transfer("JBPNPULUUASL9XVIJI9AS9LPSQMTTDEPUSKJZGGIPJ9EUAWXW9TKADWHNGSMTHITJR9UMGW9CIFTHUXG9WCLOLUAAZ", 100, TrytesConverter.toTrytes("This is a test-message"), "999999999999999999999999999");
	List<Transfer> transfers = new ArrayList<Transfer>(); transfers.add(transfer);
			
	proxy.sendTransfer(seed, 3, 100, 14, transfers, new Input[]{rsp.getInput().get(0)}, "JBPNPULUUASL9XVIJI9AS9LPSQMTTDEPUSKJZGGIPJ9EUAWXW9TKADWHNGSMTHITJR9UMGW9CIFTHUXG9WCLOLUAAZ");

During the run of java-program I get the input like this :

jota.dto.response.GetBalancesAndFormatResponse@6276ae34[ input=[jota.model.Input@32e6e9c3[ address=SRIVO9VGLUWGHFMXAFUFQRTWPTZWN9PJ9Y9AFDUFQNXMEPJYPFEPKNGBPNWYTOHSWWCWKGNFMWNGDDPPW balance=100 keyIndex=0 security=3 ]] totalBalance=100 duration=559 ]
which then should be just right.
The transaction that is made, however is not good. Both the extra zero-valued transactions has the same signature. Since I now use level 3 there is created two zero-txes for holding the extra signature-parts, but they contain the same value. So the signature is invalid.

If I use js-lib to send, It works ok.

This is a sampel of a bundle that has wrong signature from java-lib : OPCDDUNRWKCXZBGMIUTEJBTRWIRHRRKLSJMALTANADHVLKAPQBXJECLZEHLRHCICTKRRDCTIJYPVA9999

I also have a question ....
In the class GetBalancesAndFormatResponse the inputs are returned as a list.
the sendTransfer-method requires an array, and one of the first things done in this method is to convert the array to a list --- What's the point ?

wereAddressesSpentFrom feature solution for adding to JOTA

Sorry, cant Git push, my library is too different lots of copy paste but should be fairly easy

Adding wereAddressesSpentFrom feature to JOTA


jota.IotaApiService.java

--- add this to the file

    /**
     * Returns information about and address and if it has be used before (spent from).
     * <p>
     * {@code curl http://localhost:14265 -X POST -H 'X-IOTA-API-Version: 1.4.1' -H 'Content-Type: application/json'}
     * -d '{"command": "wereAddressesSpentFrom", "addresses": ["RVORZ9SIIP9RCYMREUIXXVPQIPHVCNPQ9HZWYKFWYWZRE9JQKG9REPKIASHUUECPSQO9JT9XNMVKWYGVAZETAIRPTM"]}'
     */
    @Headers({CONTENT_TYPE_HEADER, USER_AGENT_HEADER})
    @POST("./")
    Call<WereAddressesSpentFromResponse> wereAddressesSpentFrom(@Body IotaWereAddressesSpentFromRequest request);


jota.IotaAPI.java

--- add this to the file, 2 calls, 1 for single address, 1 for multi-address, removes any checksum if they have

    public boolean[] checkWereAddressSpentFrom(String[] addresses) {
        List<String> rawAddresses=new ArrayList<>();
        for(String address: addresses) {
            String rawAddress=null;
            try {
                if (Checksum.isAddressWithChecksum(address)) {
                    rawAddress=Checksum.removeChecksum(address);
                }
            } catch (ArgumentException e) {}
            if(rawAddress==null)
                rawAddresses.add(address);
            else
                rawAddresses.add(rawAddress);
        }
        String[] spentAddresses = new String[rawAddresses.size()];
        spentAddresses = rawAddresses.toArray(spentAddresses);
        WereAddressesSpentFromResponse response = wereAddressesSpentFrom(spentAddresses);
        return response.getStates();

    }
    public Boolean checkWereAddressSpentFrom(String address) {
        String rawAddress=address;
        try {
            if(Checksum.isAddressWithChecksum(address)) {
                rawAddress=Checksum.removeChecksum(address);
            }
        } catch (ArgumentException e) {}
        String[] spentAddresses =new String[1];
        spentAddresses[0]=rawAddress;
        WereAddressesSpentFromResponse response = wereAddressesSpentFrom(spentAddresses);
        return response.getStates()[0];
    }


jota.IotaApiCore.java

---- add to file

    public WereAddressesSpentFromResponse wereAddressesSpentFrom(String[] addresses) {
        final IotaWereAddressesSpentFromRequest wasSpentRequest = IotaWereAddressesSpentFromRequest.createWereAddressSpendFromRequest(addresses);
        final Call<WereAddressesSpentFromResponse> res =  service.wereAddressesSpentFrom(wasSpentRequest);
        return wrapCheckedException(res).body();
    }


jota.IotaAPICommands.java

--- full file

public enum IotaAPICommands {

    GET_NODE_INFO("getNodeInfo"),
    GET_NEIGHBORS("getNeighbors"),
    ADD_NEIGHBORS("addNeighbors"),
    REMOVE_NEIGHBORS("removeNeighbors"),
    GET_TIPS("getTips"),
    FIND_TRANSACTIONS("findTransactions"),
    GET_TRYTES("getTrytes"),
    GET_INCLUSIONS_STATES("getInclusionStates"),
    GET_BALANCES("getBalances"),
    GET_TRANSACTIONS_TO_APPROVE("getTransactionsToApprove"),
    ATTACH_TO_TANGLE("attachToTangle"),
    INTERRUPT_ATTACHING_TO_TANGLE("interruptAttachingToTangle"),
    BROADCAST_TRANSACTIONS("broadcastTransactions"),
    STORE_TRANSACTIONS("storeTransactions"),
    WERE_ADDRESSES_SPENT_FROM("wereAddressesSpentFrom");
    private String command;

    /**
     * Initializes a new instance of the IotaAPICommands class.
     */
    IotaAPICommands(String command) {
        this.command = command;
    }

    /**
     * Gets the command.
     *
     * @return The command.
     */
    public String command() {
        return command;
    }

}


jota.dto.response.WereAddressesSpentFromResponse.java

public class WereAddressesSpentFromResponse  extends AbstractResponse {

    private boolean[] states;

    /**
     * Gets the states.
     *
     * @return The states.
     */
    public boolean[] getStates() {
        return states;
    }

}


jota.dto.request.IotaWereAddressesSpentFromRequest.java

public class IotaWereAddressesSpentFromRequest extends IotaCommandRequest {

    private String[] addresses;

    /**
     * Initializes a new instance of the IotaWereAddressesSpentFromRequest class.
     */
    public IotaWereAddressesSpentFromRequest(final String[] addresses) {

        super(IotaAPICommands.WERE_ADDRESSES_SPENT_FROM);
        this.addresses = addresses;
    }

    /**
     * Create a new instance of the IotaWereAddressesSpentFromRequest class.
     */
    public static IotaWereAddressesSpentFromRequest createWereAddressSpendFromRequest(String[] addresses) {
        return new IotaWereAddressesSpentFromRequest(addresses);
    }


    public String[] getAddresses() {
        return addresses;
    }

    public void setAddresses(String[] addresses) {
        this.addresses = addresses;
    }
}

findTailTransactionHash

Hi,

I'm implementing a C++ version of this library and I spent some time checking your code.
However, I got confused by your findTailTransactionHash.

From the documentation, it should return a tail transaction hash given a transaction hash.
The thing I don't get is that if the input transaction is not a tail transaction, you recursively call the function with the hash of the bundle which is then used to init a transaction object.
On my C++ port, this does not work and returns an empty hash (hash full of 9's), which limits the use of this function (because it seems it only return the tail transaction hash if the input transaction is a tail).

I tried to check on other implementation but seems this function is only provided on the java client.

Is there something I missed or is there a bug in this function?

On my implementation, I replaced the else branch by a call to findTransactionObjectsByBundle with the bundle hash of the input trx followed by a loop finding the tail transaction.

IotaAPI bug and fix on Address security values

This is part of a bigger issue I am investigating around Address security, will be posting more fixes as and when I find them.

IotaAPI.java
line 1120
bundle.addEntry(security, inputs.get(i).getAddress(), toSubtract, tag, timestamp);

should be

bundle.addEntry(inputs.get(i).getSecurity(), inputs.get(i).getAddress(), toSubtract, tag, timestamp);

Essentially it's passing in the default security when it should be passing the Addresses security it could be different)

Sorry I have not done a git push request, the library I work from has been stripped to remove most of the Stateless function for speed so cant do a push, it would be a mess and bad.

Documentation

I'm starting to playing with this lib but unfortunately I'm not managing to do anything without read the source code frequently.

Could you guys provide some examples in the README? I'm pretty sure I'm not the only one.

I.E.:

  • Performing a transfer using attachToTangle
  • Performing a transfer using PoW locally
  • Check if a transaction is confirmed
    etc

Maven installation problem: Could not resolve dependencies

Been facing dependencies installation issues, for installing jota locally.

jota bug 1
As you can see in the above image, this is the index which maven resolves to leveraging the pom.xml.
However the pom.xml file in the index redirects to other directory. Which is called jota.

<dependency>
<groupId>com.github.iotaledger.iota.lib.java</groupId>
<artifactId>jota</artifactId>
<version>0.9.7</version>
</dependency>

jota bug 2
However if you traverse directly to this directory, jitpack says it doesn't exist. The below image suffices maven's order of fetching the jar.
jota bug 3

There are two possiblities. Either the jota directory on that index is deleted or restricted.
Someone with access to jitpack could resolve the issue.

jota bug 4
Another thing is that, the jar is sitting right there for the latest version, however the pom.xml is still redirecting to jota directory.

Expand IotaApi.java test coverage for getBundle

From PR #65, there was a bug in retrieving bundles with a signature size greater than 2. I would recommend, and request, that tests be added to assure that it can handle bundles with arbitrary signature sizes.

Potential for race condition in signing.java

The signing class keeps and uses an instance of an ICurl, but member functions are not synchronized. See here:
https://github.com/iotaledger/iota.lib.java/blob/fbacc5ae44e246b8361be3586ac6c0d28b6aac2f/jota/src/main/java/jota/utils/Signing.java#L32

For the most minimal change, I suggest to not keep an instance of an ICurl in this class - but, at the very least, change this to a SpongeFactory mode, and create an instance inside each method that uses it.

TrytesConverter doesn't work properly

Everytime I try to convert some trytes to bytes i get this error, whatever is the lenght of the trytes....

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 195
at java.lang.String.charAt(String.java:658)
at jota.utils.TrytesConverter.toString(TrytesConverter.java:81)
at com.france193.Main.main(Main.java:50)

Dependency problem

Hi,

I know that there was a closed issue on this matter: #72.

However, I am still experiencing this problem when trying to use the latest version (v0.9.10) of iota, it works with v0.9.6 though.

I am using this approach:
To use the IOTA Java library in your Maven build add this to your root pom.xml file:

 <repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

Add this in your module pom.xml file:

<dependency>
    <groupId>com.github.iotaledger</groupId>
    <artifactId>iota~lib~java</artifactId>
    <version>0.9.10</version>
</dependency>

I am facing the following problem:

Could not resolve dependencies for project com.mycompany.app:my-app:jar:1.0-SNAPSHOT: Failed to collect dependencies at com.github.iotaledger:iota.lib.java:jar:v0.9.10 -> com.github.iotaledger.iota.lib.java:jota:jar:v0.9.10: Failed to read artifact descriptor for com.github.iotaledger.iota.lib.java:jota:jar:v0.9.10: Could not transfer artifact com.github.iotaledger.iota.lib.java:jota:pom:v0.9.10 from/to jitpack.io (https://jitpack.io): Not authorized , ReasonPhrase:Unauthorized. -> [Help 1]

Any idea?

Thanks,
Dan

IotaAPI.getTransfers() always throws ArgumentException for specific (seed, index) combinations

When calling this method:

api.getTransfers(seed, 2, index, index+1, false);

I frequently receive this exception:

jota.error.ArgumentException: [{"error":"Could not complete request","duration":43}]
    at jota.IotaAPICore.wrapCheckedException(IotaAPICore.java:71)
    at jota.IotaAPICore.getTrytes(IotaAPICore.java:292)
    at jota.IotaAPI.findTransactionsObjectsByHashes(IotaAPI.java:268)
    at jota.IotaAPI.findTransactionObjectsByAddresses(IotaAPI.java:297)
    at jota.IotaAPI.bundlesFromAddresses(IotaAPI.java:132)
    at jota.IotaAPI.getTransfers(IotaAPI.java:116)

Furthermore, this exception only happens for very specific (seed, index) combinations. So it works for the paramers (seed = 'PDIZO...', index = 29), but not for (seed = 'PDIZO...', index = 30). I can call the latter one a hundred times, yet the exception will continue to be thrown every single time. I have tried connecting to different nodes, but this did not help either.

For obvious reason, I will not post any explicit seed in here. If, however, any developer of this repository wants to replicate the error, I will happily provide you with an example seed with a rather low balance.

Also, I'm using the latest snapshot of v0.9.11, not sure whether that's the issue. I'm 80% sure it already happened to me when using v0.9.6.

`Signing` class cannot create old CURL addresses

While the Signing class constructor can be used to pass a Curl implementation (both Curl and Kerl) into the class, it cannot be used for generating Curl addresses, as some parts of the class will ignore the passed in Curl implementation but instead create a new one of type Kerl.

Not sure how useful this feature is in practice - it cost me 3 hours of searching why my Curl signatures did not match, though.

So should we remove the possibility to choose the hash function or make it work?

Tag is not accurate

If use IotaAPI.sendTransfer send three meta transaction with three specified diffrent tag, and more with a value transfer transaction, the last one tag will be used in the input transaction and signature output meta transaction and remainder output transaction, which is not match with the expected.
Please see this:
https://github.com/iotaledger/iota.lib.java/blob/42e1eb5fd5a2938ac417449f213c3a1f8e1bd8d6/jota/src/main/java/jota/IotaAPI.java#L422
The tag is not reset to empty when code run out of the for loop, and will effect the following code:
https://github.com/iotaledger/iota.lib.java/blob/42e1eb5fd5a2938ac417449f213c3a1f8e1bd8d6/jota/src/main/java/jota/IotaAPI.java#L447
https://github.com/iotaledger/iota.lib.java/blob/42e1eb5fd5a2938ac417449f213c3a1f8e1bd8d6/jota/src/main/java/jota/IotaAPI.java#L486
https://github.com/iotaledger/iota.lib.java/blob/42e1eb5fd5a2938ac417449f213c3a1f8e1bd8d6/jota/src/main/java/jota/IotaAPI.java#L497

My opinon is to change the tag variable to in-loop local variable, and remove the tag parameter from the addRemainder method. The tag parameter is not passed from the IotaAPI.sendTransfer method after all.
https://github.com/iotaledger/iota.lib.java/blob/42e1eb5fd5a2938ac417449f213c3a1f8e1bd8d6/jota/src/main/java/jota/IotaAPI.java#L1104-L1111
There is no tag parameter in sendTransfer method declaration.
https://github.com/iotaledger/iota.lib.java/blob/42e1eb5fd5a2938ac417449f213c3a1f8e1bd8d6/jota/src/main/java/jota/IotaAPI.java#L815

Problem with method "getBundle" which include many transactions (more 100 for example)

When transaction in bundle with many transactions, methods "bundlesFromAddresses" and "getBundle" don`t return this transactions. We have used one of this method instead "findTransactionObjectsByAddresses" because we need "persistance" value (need to know is transaction confirmed).
Transaction example: "VC9KNL9RQAMPIZ9YGSJZSQCJRXEULQWBFAL9NTPNMDAXFLOLQALNXXLLIAKWZGSXEATFPT9VPHUO99999"

sendTransfer breaks tag for first transaction in bundle

If we makes transfer with or without sending tokens, the first transactions come out with a broken tag for the first trithes.

String tag = "AAAAAAAAAAAAA";

first transaction in bundle:
obsoleteTag=HDBAAAAAAAAAA99999999999999
tag=HDBAAAAAAAAAA99999999999999

second and subsequent transactions in bundle are normal:
obsoleteTag=AAAAAAAAAAAAA99999999999999
tag=AAAAAAAAAAAAA99999999999999

library is automatically catching and printStackTracing ArgumentException when receiving 400 error from getTransactionsToApprove()

https://github.com/iotaledger/iota.lib.java/blob/39c6442d941e03ea9cb0e0598f32129dec28057e/jota/src/main/java/jota/IotaAPICore.java#L72

Maybe this is intentional, but I don't get how this is useful. This exception is thrown when calling IotaAPICore.getTransactionsToApprove(), but receiving a 400 error from the IRI (very common: [{"error":"inconsistent tips pair selected","duration":4630}]).

But since the exception is catched, the program will just continue to be executed and return the call reponse - in contrast to a 401 or 500 error where an IllegalAccessError is thrown correctly. That means that anyone calling IotaAPICore.getTransactionsToApprove(), will not be informed about a 400 error during the request.

incorrect address checksum after IOTA updated

After last update IOTA, genereted address doesnt accept in lightwallet, its return "Incorrect address checksum". And transfers created by iota.lib after some time with status "failed" in iota explorer.

Add a few sentences on how to contribute to the project

Please, add a CONTRIBUTING.md with the instructions on how to contribute to this project. For instance, should I expect master to be the currently on development branch, like other open source projects? Should I expect the tests to pass on the repository's CI?

"Invalid API Version" after update to IRI 1.4.1

Exception in thread "main" java.lang.IllegalAccessError: 400 {"error":"Invalid API Version","duration":0}
at jota.IotaAPICore.wrapCheckedException(IotaAPICore.java:58)
at jota.IotaAPICore.getNodeInfo(IotaAPICore.java:111)
at france193.IOTANode.getNodeInfo(IOTANode.java:59)
at france193.Main.main(Main.java:19)

IotaAPI#prepareTransfers does not consume remainder

Just take a look at the source, it doesn't seem like the remainder parameter is ever used.
Reproduction is as simple as
String remainderAddress = ...; List<String> transfers = iotaAPI.prepareTransfers(seed, 2, transfers, remainderAddress, inputs); for(String trytes : transfers) System.out.println(remainderAddress.equals(new Transaction(trytes).getAddress());
this snippet will never return true as the remainderAddress is always generated!

Maven issue

I'm getting:
Could not resolve dependencies for project com.mycompany.app:my-app:jar:1.0-SNAPSHOT: Failed to collect dependencies at com.github.iotaledger:iota.lib.java:jar:v0.9.10 -> com.github.iotaledger.iota.lib.java:jota:jar:v0.9.10: Failed to read artifact descriptor for com.github.iotaledger.iota.lib.java:jota:jar:v0.9.10: Could not transfer artifact com.github.iotaledger.iota.lib.java:jota:pom:v0.9.10 from/to jitpack.io (https://jitpack.io): Not authorized , ReasonPhrase:Unauthorized. -> [Help 1]

When I try use this library in a maven project. Any ideas?

Can not send a transaction,

I used iota java library 0.9.11

and got an exception

jota.error.ArgumentException: [{"error":"starting tip failed consistency check: VAZRZILTVSZKOELMJSHTBHHUYJZON9LRBYMCDBKZMKXIKFVTRVZFEGXJXSRXBEPOUVFESMDBCYYC99999","duration":1474}]
at jota.IotaAPICore.wrapCheckedException(IotaAPICore.java:71)
at jota.IotaAPICore.getTransactionsToApprove(IotaAPICore.java:303)
at jota.IotaAPI.sendTrytes(IotaAPI.java:236)
at jota.IotaAPI.sendTransfer(IotaAPI.java:825)
at iotatest.test1.shouldSendTransfer(test1.java:72)
at iotatest.IotaTest.main(IotaTest.java:39)

with code

IotaAPI api = new IotaAPI.Builder()
.localPoW(new PearlDiverLocalPoW())
.protocol("http")
.host("eugene.iota.community")
.port("14265")
.build();

    String seed = "seed";
    String tag2 = "UPDATE999999999999999999999";
    String sendToAddress = "NYYVQVJMQVYCB9AQXTYFQOZP99R9GRIYRJV9MYIJKTBNXRMAGDXJQWYFKCXBPRLRPBZRRHRZOZTFEWJXBIRWEEGCTW";
    List<Transfer> transfers = new ArrayList<>();
    transfers.add(new jota.model.Transfer(sendToAddress, 0, "ATTACH", tag2));
    jota.dto.response.SendTransferResponse str = api.sendTransfer(seed, 2, 5, 14, transfers, null, null, false, false);
    System.out.println(java.util.Arrays.toString(str.getSuccessfully()));

Travis and releases

Currently, the Travis builds aren't working for PRs. Similarly, it's not clear how a release is made. In fact, it appears that artifacts aren't being released to Maven Central yet.

If there's agreement, I would like to:

  • Request a new project with Sonatype, to publish artifacts on Maven Central
  • Create a bintray project for this repository
  • Deprecate the dev branch, by having all development happening on master, as it's usual for open source projects. For that, I'd just "force push" the current dev to master and remove the dev branch. Note that the version in the pom.xml for master is always -SNAPSHOT
  • Fix Travis to have a build in stages. For instance, this could be used as a reference: https://github.com/opentracing-contrib/java-ejb/blob/master/.travis.yml
  • With a setup like the above, creating a new release is just a matter of pushing a tag named release-x.x.x, where x.x.x is the version to be released
  • Document this process by adding a RELEASE.md document

Error with GetAccountDataResponse

Error with GetAccountDataResponse
Code:

                api = new IotaAPI.Builder()
                        .protocol("https")
                        .host("node.iota-community.org")
                        .port("")
                        .build();
                GetAccountDataResponse response = null;
                try {
                    response = api.getAccountData(
                            "MYSEED",
                            2,
                            0,
                            true,
                            0,
                            true,
                            0,
                            0,
                            true,
                            0
                    );
                    Log.d("getNewAddress", response.toString());
                } catch (ArgumentException e) {
                    e.printStackTrace();
                }

Error:
02-24 17:47:24.841 6850-6964/org.iota.community.wallet W/System.err: jota.error.ArgumentException: [{"error":"Could not complete request","duration":417}]
02-24 17:47:24.842 6850-6964/org.iota.community.wallet W/System.err: at jota.IotaAPICore.wrapCheckedException(IotaAPICore.java:71)
02-24 17:47:24.843 6850-6964/org.iota.community.wallet W/System.err: at jota.IotaAPICore.getTrytes(IotaAPICore.java:292)
02-24 17:47:24.843 6850-6964/org.iota.community.wallet W/System.err: at jota.IotaAPI.findTransactionsObjectsByHashes(IotaAPI.java:268)
02-24 17:47:24.843 6850-6964/org.iota.community.wallet W/System.err: at jota.IotaAPI.findTransactionObjectsByAddresses(IotaAPI.java:297)
02-24 17:47:24.844 6850-6964/org.iota.community.wallet W/System.err: at jota.IotaAPI.bundlesFromAddresses(IotaAPI.java:132)
02-24 17:47:24.844 6850-6964/org.iota.community.wallet W/System.err: at jota.IotaAPI.getTransfers(IotaAPI.java:116)
02-24 17:47:24.845 6850-6964/org.iota.community.wallet W/System.err: at jota.IotaAPI.getAccountData(IotaAPI.java:736)
02-24 17:47:24.845 6850-6964/org.iota.community.wallet W/System.err: at cordova.plugin.iota.iota$1.run(iota.java:43)
02-24 17:47:24.846 6850-6964/org.iota.community.wallet W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
02-24 17:47:24.847 6850-6964/org.iota.community.wallet W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
02-24 17:47:24.849 6850-6964/org.iota.community.wallet W/System.err: at java.lang.Thread.run(Thread.java:764)

                                                                 --------- beginning of crash

02-24 17:47:24.856 6850-6964/org.iota.community.wallet E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-2
Process: org.iota.community.wallet, PID: 6850
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] jota.dto.response.GetTrytesResponse.getTrytes()' on a null object reference
at jota.IotaAPI.findTransactionsObjectsByHashes(IotaAPI.java:272)
at jota.IotaAPI.findTransactionObjectsByAddresses(IotaAPI.java:297)
at jota.IotaAPI.bundlesFromAddresses(IotaAPI.java:132)
at jota.IotaAPI.getTransfers(IotaAPI.java:116)
at jota.IotaAPI.getAccountData(IotaAPI.java:736)
at cordova.plugin.iota.iota$1.run(iota.java:43)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)

Show the optional field on document and function comment

Redirecting the original issue opened in JS repo: iotaledger/iota.js#261
@thieuanh1995hn wrote:
"Hi guys i think you should show us that what field can define null (optional) on Java Client API which you have done well in Java script library : https://iotaledger.github.io/iota.lib.java/javadoc/jota/IotaAPI.html#sendTransfer-java.lang.String-int-int-int-java.util.List-java.util.List-java.lang.String-boolean-boolean-
For example. In sendTransfer Api . We can define inputs parameter = null because it is optional and the code show that truth."

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.