Code Monkey home page Code Monkey logo

java-bigchaindb-driver's Introduction

Build Status Gitter java-bigchaindb-driver

Official Java and Android Driver for BigchainDB

Please note: This driver is compatible with Android API 23 and later.

Compatibility

BigchainDB Server BigchainDB Java Driver
2.x 1.x

Contents

Installation

The build system supports both Maven and Gradle.

Maven Users

In your pom.xml file, add bigchaindb-driver as a dependency:

<dependency>
	<groupId>com.bigchaindb</groupId>
	<artifactId>bigchaindb-driver</artifactId>
	<version>1.0</version>
</dependency>

then

mvn clean install

Gradle Users

In your build.gradle file, add bigchaindb-driver as a dependency:

dependencies {
    implementation 'com.bigchaindb.bigchaindb-driver:1.2'
    }

then

./gradlew install

Usage

A sample of an end-to-end CREATE and TRANSFER operation is available in the gist https://gist.github.com/innoprenuer/d4c6798fe5c0581c05a7e676e175e515

Set Up Your Configuration

Single-Node Setup

BigchainDbConfigBuilder
	.baseUrl("https://node1.example.com/")
	.addToken("header1", <header1_value>)
	.addToken("header2", <header2_value>).setup();

Multi-Node Setup (More Robust and Reliable)

Note - multi-node setup is only available in version 1.2 and later

Assumption - The following setup assumes that all nodes are all connected within same BigchainDB network.

	//define connections
    Map<String, Object> conn1Config = new HashMap<String, Object>(), 
                 conn2Config = new HashMap<String, Object>();
    
    //define headers for connections
    Map<String, String> headers1 = new HashMap<String, String>();
    Map<String, String> headers2 = new HashMap<String, String>();
    
    //config header for connection 1
    headers1.put("app_id", "<your-app-id>");
    headers1.put("app_key", "<your-app-key>");
    
    //config header for connection 2
    headers2.put("app_id", "<your-app-id>");
    headers2.put("app_key", "<your-app-key>");
    
    //config connection 1
    conn1Config.put("baseUrl", "https://node1.mysite.com/");
    conn1Config.put("headers", headers1);
    Connection conn1 = new Connection(conn1Config);
    
    //config connection 2
    conn2Config.put("baseUrl", "https://node2.mysite.com/");
    conn2Config.put("headers", headers2);
    Connection conn2 = new Connection(conn2Config);
    
    //add connections
    List<Connection> connections = new ArrayList<Connection>();
    connections.add(conn1);
    connections.add(conn2);
    //...You can add as many nodes as you want
    
    BigchainDbConfigBuilder
    .addConnections(connections)
    .setTimeout(60000) //override default timeout of 20000 milliseconds
    .setup();
    
    }  

Example: Prepare Keys, Assets and Metadata

// prepare your keys
net.i2p.crypto.eddsa.KeyPairGenerator edDsaKpg = new net.i2p.crypto.eddsa.KeyPairGenerator();
KeyPair keyPair = edDsaKpg.generateKeyPair();

// New asset
Map<String, String> assetData = new TreeMap<String, String>() {{
    put("city", "Berlin, DE");
    put("temperature", "22");
    put("datetime", new Date().toString());
}};

// New metadata
MetaData metaData = new MetaData();
metaData.setMetaData("what", "My first BigchainDB transaction");

Example: Create an Asset

Performing a CREATE transaction in BigchainDB allocates or issues a digital asset.

// Set up, sign, and send your transaction
Transaction createTransaction = BigchainDbTransactionBuilder
	.init()
	.addAssets(assetData, TreeMap.class)
	.addMetaData(metaData)
	.operation(Operations.CREATE)
	.buildAndSign((EdDSAPublicKey) keyPair.getPublic(), (EdDSAPrivateKey) keyPair.getPrivate())
	.sendTransaction();

Example: Transfer an Asset

Performing a TRANSFER transaction in BigchainDB changes an asset's ownership (or, more accurately, authorized signers):

// Generate a new keypair to TRANSFER the asset to
KeyPair targetKeypair = edDsaKpg.generateKeyPair();

// Describe the output you are fulfilling on the previous transaction
final FulFill spendFrom = new FulFill();
spendFrom.setTransactionId(createTransaction.getId());
spendFrom.setOutputIndex(0);

// Change the metadata if you want
MetaData transferMetadata = new MetaData();
metaData.setMetaData("what2", "My first BigchainDB transaction");

// the asset's ID is equal to the ID of the transaction that created it
String assetId = createTransaction.getId();

// By default, the 'amount' of a created digital asset == "1". So we spend "1" in our TRANSFER.
String amount = "1";

// Use the previous transaction's asset and TRANSFER it
Transaction transferTransaction = BigchainDbTransactionBuilder
	.init()
	.addMetaData(metaData)

	// source keypair is used in the input, because the current owner is "spending" the output to transfer it
	.addInput(null, spendFrom, (EdDSAPublicKey) keyPair.getPublic())

	// after this transaction, the target 'owns' the asset, so, the new output includes the target's public key
	.addOutput(output, (EdDSAPublicKey) targetKeypair.getPublic())

	// reference the asset by ID when doing a transfer
	.addAssets(assetId, String.class)
	.operation(Operations.TRANSFER)

	// the source key signs the transaction to authorize the transfer
	.buildAndSign((EdDSAPublicKey) keyPair.getPublic(), (EdDSAPrivateKey) keyPair.getPrivate())
	.sendTransaction();

Example: Setup Config with WebSocket Listener

public class MyCustomMonitor implements MessageHandler {
	@Override
	public void handleMessage(String message) {
		ValidTransaction validTransaction = JsonUtils.fromJson(message, ValidTransaction.class);
	}
}

// config
BigchainDbConfigBuilder
	.baseUrl("https://api.example.net")
	.addToken("app_id", "2bbaf3ff")
	.addToken("app_key", "c929b708177dcc8b9d58180082029b8d")
	.webSocketMonitor(new MyCustomMonitor())
	.setup();

More Examples

Example: Create a Transaction (without signing and without sending)

// Set up your transaction but only build it
Transaction transaction = BigchainDbTransactionBuilder
	.init()
	.addAssets(assetData, TreeMap.class)
	.addMetaData(metaData)
	.operation(Operations.CREATE)
	.buildOnly((EdDSAPublicKey) keyPair.getPublic());

Example: Create and Sign Transaction (without sending it to the ledger)

//    Set up your transaction
Transaction transaction = BigchainDbTransactionBuilder
	.init()
	.addAssets(assetData, TreeMap.class)
	.addMetaData(metaData)
	.operation(Operations.CREATE)
	.buildAndSignOnly((EdDSAPublicKey) keyPair.getPublic(), (EdDSAPrivateKey) keyPair.getPrivate());

API Wrappers

Transactions

Send a Transaction

TransactionsApi.sendTransaction(Transaction transaction) throws IOException

Send a Transaction with Callback

TransactionsApi.sendTransaction(Transaction transaction, final GenericCallback callback) 

Get Transaction given a Transaction Id

Transaction TransactionsApi.getTransactionById(String id) throws IOException

Get Transaction given an Asset Id

Transactions TransactionsApi.getTransactionsByAssetId(String assetId, Operations operation)

Outputs

Get Outputs given a public key

Outputs getOutputs(String publicKey) throws IOException

Get Spent Outputs given a public key

Outputs getSpentOutputs(String publicKey) throws IOException

Get Unspent Outputs given a public key

Outputs getUnspentOutputs(String publicKey) throws IOException

Assets

Get Assets given search key

Assets getAssets(String searchKey) throws IOException

Get Assets given search key and limit

Assets getAssetsWithLimit(String searchKey, String limit) throws IOException

Blocks

Get Blocks given block id

Block getBlock(String blockId) throws IOException

Get Blocks given transaction id

List<String> getBlocksByTransactionId(String transactionId) throws IOException

MetaData

Get MetaData given search key

MetaDatas getMetaData(String searchKey) throws IOException

Get MetaData given search key and limit

MetaDatas getMetaDataWithLimit(String searchKey, String limit) throws IOException

Validators

Gets the the local validators set of a given node

Validators getValidators() throws IOException

BigchainDB Documentation

Authors

Inspired by http://github.com/authenteq/java-bigchaindb-driver.

The BigchainDB team and others including:

  • @bodia
  • @alvin-reyes
  • @agwego
  • @nf-PostQuantum
  • @Rokko11
  • @tzclucian
  • @kremalicious
  • @avanaur
  • @GerardoGa
  • @bakaoh
  • @innoprenuer

Release Process

To execute a release build with Maven, define performRelease to enable GPG signing:

mvn clean package install -DperformRelease

Licenses

See LICENSE and LICENSE-docs.

Exception: src/main/java/com/bigchaindb/util/Base58.java has a different license; see the comments at the top of that file for more information.

java-bigchaindb-driver's People

Contributors

innopreneur avatar kai18 avatar ttmc 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-bigchaindb-driver's Issues

how I can build transactions.recipients?

why BigchainDbTransactionBuilder.class don`t have the interface about" addRecipients()",
your demo transaction just change the Metadata for by asset owner,
how to make asset from A to B?

mvn clean install failing due to failing tests

In the project and master branch, doing
mvn clean install
It fails due to :

Tests run: 4, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.108 sec <<< FAILURE! - in com.bigchaindb.api.BlocksApiTest
testGetBlock(com.bigchaindb.api.BlocksApiTest)  Time elapsed: 0.011 sec  <<< ERROR!
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Not a JSON Array: {"sequence":0}
	at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:107)
	at com.bigchaindb.json.strategy.MetaDataDeserializer.deserialize(MetaDataDeserializer.java:26)
	at com.bigchaindb.json.strategy.MetaDataDeserializer.deserialize(MetaDataDeserializer.java:16)
	at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
	at com.google.gson.Gson.fromJson(Gson.java:888)
	at com.google.gson.Gson.fromJson(Gson.java:853)
	at com.google.gson.Gson.fromJson(Gson.java:802)
	at com.google.gson.Gson.fromJson(Gson.java:774)
	at com.bigchaindb.util.JsonUtils.fromJson(JsonUtils.java:127)
	at com.bigchaindb.json.strategy.TransactionDeserializer.deserialize(TransactionDeserializer.java:46)
	at com.bigchaindb.json.strategy.TransactionDeserializer.deserialize(TransactionDeserializer.java:18)
	at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
	at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
	at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
	at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
	at com.google.gson.Gson.fromJson(Gson.java:888)
	at com.google.gson.Gson.fromJson(Gson.java:853)
	at com.google.gson.Gson.fromJson(Gson.java:802)
	at com.google.gson.Gson.fromJson(Gson.java:774)
	at com.bigchaindb.util.JsonUtils.fromJson(JsonUtils.java:127)
	at com.bigchaindb.api.BlocksApi.getBlock(BlocksApi.java:35)
	at com.bigchaindb.api.BlocksApiTest.testGetBlock(BlocksApiTest.java:72)

No Line Found error when running tests in com.bigchaindb.ws.BigchainDbWSSessionManager

Running com.bigchaindb.api.TransactionApiTest
20180808-10:57:35 1255 [main] DEBUG org.eclipse.jetty.util.component.Container  - Container org.eclipse.jetty.server.Server@6f44a157 + [email protected]:0 as connector
20180808-10:57:35 1256 [main] DEBUG net.jadler.JadlerMocker  - starting the underlying stub server...
20180808-10:57:35 1256 [main] DEBUG org.eclipse.jetty.util.component.Container  - Container org.eclipse.jetty.server.Server@6f44a157 + net.jadler.stubbing.server.jetty.JadlerHandler@6bc407fd as handler
20180808-10:57:35 1256 [main] DEBUG net.jadler.stubbing.server.jetty.JettyStubHttpServer  - starting jetty
20180808-10:57:35 1256 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - starting org.eclipse.jetty.server.Server@6f44a157
20180808-10:57:35 1256 [main] INFO  org.eclipse.jetty.server.Server  - jetty-8.1.11.v20130520
20180808-10:57:35 1256 [main] DEBUG org.eclipse.jetty.util.component.Container  - Container org.eclipse.jetty.server.Server@6f44a157 + qtp2694936{8<=0<=0/254,-1} as threadpool
20180808-10:57:35 1257 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - starting net.jadler.stubbing.server.jetty.JadlerHandler@6bc407fd
20180808-10:57:35 1257 [main] DEBUG org.eclipse.jetty.server.handler.AbstractHandler  - starting net.jadler.stubbing.server.jetty.JadlerHandler@6bc407fd
20180808-10:57:35 1257 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - STARTED net.jadler.stubbing.server.jetty.JadlerHandler@6bc407fd
20180808-10:57:35 1257 [main] DEBUG org.eclipse.jetty.server.handler.AbstractHandler  - starting org.eclipse.jetty.server.Server@6f44a157
20180808-10:57:35 1257 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - starting qtp2694936{8<=0<=0/254,-1}
20180808-10:57:35 1260 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - STARTED qtp2694936{8<=8<=8/254,0}
20180808-10:57:35 1260 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - starting [email protected]:0
20180808-10:57:35 1260 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - starting null/null
20180808-10:57:35 1261 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - STARTED PooledBuffers [0/1024@6144,0/1024@16384,0/1024@-]/PooledBuffers [0/1024@6144,0/1024@32768,0/1024@-]
20180808-10:57:35 1261 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - starting org.eclipse.jetty.server.nio.SelectChannelConnector$ConnectorSelectorManager@17d88132
20180808-10:57:35 1261 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - STARTED org.eclipse.jetty.server.nio.SelectChannelConnector$ConnectorSelectorManager@17d88132
20180808-10:57:35 1261 [qtp2694936-93 Selector0] DEBUG org.eclipse.jetty.io.nio  - Starting Thread[qtp2694936-93 Selector0,5,main] on org.eclipse.jetty.io.nio.SelectorManager$1@62b87516
20180808-10:57:35 1261 [main] INFO  org.eclipse.jetty.server.AbstractConnector  - Started [email protected]:56359
20180808-10:57:35 1262 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - STARTED [email protected]:56359
20180808-10:57:35 1262 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle  - STARTED org.eclipse.jetty.server.Server@6f44a157
20180808-10:57:35 1262 [main] DEBUG net.jadler.stubbing.server.jetty.JettyStubHttpServer  - jetty started
20180808-10:57:35 1262 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1262 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1262 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1262 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1262 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1262 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1262 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1263 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1263 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1263 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1263 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1264 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1264 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1264 [main] DEBUG net.jadler.JadlerMocker  - adding new stubbing...
20180808-10:57:35 1265 [main] DEBUG com.bigchaindb.builders.BigchainDbConfigBuilder  - http://localhost:56359
20180808-10:57:35 1266 [qtp2694936-93 Selector0] DEBUG org.eclipse.jetty.io.nio  - created SCEP@2d429d0a{l(/127.0.0.1:56360)<->r(/127.0.0.1:56359),s=0,open=true,ishut=false,oshut=false,rb=false,wb=false,w=true,i=0}-{AsyncHttpConnection@c734d71,g=HttpGenerator{s=0,h=-1,b=-1,c=-1},p=HttpParser{s=-14,l=0,c=0},r=0}
20180808-10:57:35 1267 [qtp2694936-95] DEBUG org.eclipse.jetty.http.HttpParser  - filled 0/0
20180808-10:57:35 1274 [qtp2694936-96] DEBUG org.eclipse.jetty.http.HttpParser  - filled 181/181
20180808-10:57:35 1274 [qtp2694936-96 - /api/v1] DEBUG org.eclipse.jetty.server.Server  - REQUEST /api/v1 on AsyncHttpConnection@c734d71,g=HttpGenerator{s=0,h=-1,b=-1,c=-1},p=HttpParser{s=-5,l=12,c=0},r=1
20180808-10:57:35 1275 [qtp2694936-96 - /api/v1] DEBUG net.jadler.JadlerMocker  - Following rule will be applied:
WHEN request (
  method is equalToIgnoringCase("GET") AND
  Path is "/api/v1")
THEN respond with status=200, body={
  "asset..., encoding=UTF-8, headers=(), delay=0 milliseconds
20180808-10:57:35 1275 [qtp2694936-96 - /api/v1] DEBUG org.eclipse.jetty.server.Server  - RESPONSE /api/v1  200 handled=true
20180808-10:57:35 1276 [qtp2694936-96] DEBUG org.eclipse.jetty.server.AsyncHttpConnection  - Enabled read interest SCEP@2d429d0a{l(/127.0.0.1:56360)<->r(/127.0.0.1:56359),s=1,open=true,ishut=false,oshut=false,rb=false,wb=false,w=true,i=1r}-{AsyncHttpConnection@c734d71,g=HttpGenerator{s=4,h=0,b=0,c=-1},p=HttpParser{s=0,l=12,c=0},r=1}
20180808-10:57:35 1276 [qtp2694936-96] DEBUG org.eclipse.jetty.http.HttpParser  - filled 0/0
20180808-10:57:35 1298 [Grizzly(1)] DEBUG com.bigchaindb.ws.BigchainDbWSSessionManager  - Opening Websocket
Exception in thread "Thread-69" java.lang.RuntimeException: java.util.NoSuchElementException: No line found
	at com.bigchaindb.ws.BigchainDbWSSessionManager.<init>(BigchainDbWSSessionManager.java:48)
	at com.bigchaindb.builders.BigchainDbConfigBuilder$Builder$1.run(BigchainDbConfigBuilder.java:159)
	at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: java.util.NoSuchElementException: No line found
	at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
	at com.bigchaindb.util.ScannerUtil.monitorExit(ScannerUtil.java:16)
	at com.bigchaindb.ws.BigchainDbWSSessionManager.<init>(BigchainDbWSSessionManager.java:46)
	... 2 more

Failure to send transaction to testnet

Hi,

All of a sudden (9/27 after 6 PM Berlin time) sending transactions to the testnet fails with the following failure

09-27 13:00:02.200: W/System.err(5687): javax.net.ssl.SSLHandshakeException: Connection closed by peer
09-27 13:00:02.200: W/System.err(5687): at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
09-27 13:00:02.200: W/System.err(5687): at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:351)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:299)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:268)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:160)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:256)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
09-27 13:00:02.200: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
09-27 13:00:02.201: W/System.err(5687): at com.bigchaindb.builders.BigchainDbConfigBuilder$Builder$2.intercept(BigchainDbConfigBuilder.java:199)
09-27 13:00:02.201: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
09-27 13:00:02.201: W/System.err(5687): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
09-27 13:00:02.201: W/System.err(5687): at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
09-27 13:00:02.201: W/System.err(5687): at okhttp3.RealCall.execute(RealCall.java:77)
09-27 13:00:02.201: W/System.err(5687): at com.bigchaindb.util.NetworkUtils.sendGetRequest(NetworkUtils.java:80)
09-27 13:00:02.201: W/System.err(5687): at com.bigchaindb.builders.BigchainDbConfigBuilder$Builder.setup(BigchainDbConfigBuilder.java:152)

example of asset data update

We are trying to use the driver to do an asset data update. Just like in javascript but failed to see a proper syntax. How would one update the asset with new values?
Or the only way to add addition attributes to the asset is via metadata update?

Asset data structure support

The bigchaindb specs state that an asset can be

"an associative array containing exactly one key-value pair."

in the glossary an associative array is defined as

"A collection of key/value (or name/value) pairs such that each possible key appears at most once in the collection. In JavaScript (and JSON), all objects behave as associative arrays with string-valued keys. In Python and .NET, associative arrays are called dictionaries. In Java and Go, they are called maps. In Ruby, they are called hashes. See also: Wikipedia’s articles for Associative array and Comparison of programming languages (associative array)"

The specs do not appear to place limitations on the data types for the keys and values of an associative array's records

Yet, at this point in time, the java driver support only asset data of the following types:

String
String[]
TreeMap<String, String>

When trying to execute a transaction with asset data of type other than the above, the transaction fails with "malformed" error message

For my Android app, I need to be able to have transactions with at least data of the following types:

List/ArrayList
TreeMap<String, Custom class>

The same is true of metadata. I need to be able to have metada of types

List/ArrayList
TreeMap<String, Custom class>

Java driver doesn't calculate the hash correctly

I'm using the Java driver for create a transaction that, then, it's send to our system backend in order to be sent from there.

The assets and the metadata are filled from a valid transaction also received from our backend:

Transaction createTransaction = BigchainDbTransactionBuilder
.init()
.addAssets(transaction.getAsset().getData(), TreeMap.class)
.addMetaData(transaction.getMetaData())
.operation(Operations.CREATE)
.buildAndSignOnly((EdDSAPublicKey) generatedPublic, (EdDSAPrivateKey) generatedPrivate);

sendFulfilledTransaction(createTransaction.toHashInput());

But the message The transaction's id isn't equal to the hash of its body is received when try to send the generated transaction. I think the id is not created correctly by the driver.

Thanks in advance.

Multiple Inputs will fail transaction

If you try to combine assets as described in https://www.bigchaindb.com/developers/guide/tutorial-token-launch/ it will fail.

The code only update first input fullfillment. See
this.transaction.getInputs().get(0)
.setFullFillment(Base64.encodeBase64URLSafeString(fulfillment.getEncoded()));

We fixed in upcoming release of C# driver https://github.com/Omnibasis/bigchaindb-csharp-driver

Here is a solution to proper sign fulfillments.

// based on javascript signTransaction
                    foreach (Input input in this.transaction.Inputs)
                    {
                        var transactionUniqueFulfillment = "";
                        if (input.FulFills != null)
                        {
                            FulFill fulfill = input.FulFills;
                            transactionUniqueFulfillment = jsonOrdered + fulfill.TransactionId + fulfill.OutputIndex.ToString();
                        } else
                        {
                            transactionUniqueFulfillment = jsonOrdered;
                        }
                        var transactionHash = DriverUtils.getSha3HashHex(transactionUniqueFulfillment);
                        var b = Utils.StringToByteArray(transactionHash);
                        var sig = algorithm.Sign(key, b);
                        Ed25519Sha256Fulfillment ff = new Ed25519Sha256Fulfillment(this.publicKey, sig);
                        input.FulFillment = Base64UrlEncoder.Encode(ff.Encoded);
                    }

Jadler test dependency missing

It seems like Jadler is used for mocking, but there is no test dependency for it listed in Gradle. I'm assuming a dev has it somewhere in their global state ;)

I can not get Validators

when I use ValidatorsApi to get the validators, I get null. My code is :
Validators validators = ValidatorsApi.getValidators(); System.out.println(validators.getValidators().get(0).getPower());

Java driver generates invalid signature

It looks that the problem is caused by double number:

import com.bigchaindb.builders.BigchainDbConfigBuilder;
import com.bigchaindb.builders.BigchainDbTransactionBuilder;
import com.bigchaindb.constants.Operations;
import com.bigchaindb.model.GenericCallback;
import com.bigchaindb.model.MetaData;
import com.bigchaindb.model.Transaction;
import net.i2p.crypto.eddsa.EdDSAPrivateKey;
import net.i2p.crypto.eddsa.EdDSAPublicKey;
import okhttp3.Response;

import java.io.IOException;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws Exception {
        BigchainDbConfigBuilder
            .baseUrl("https://test.bigchaindb.com/")
            .addToken("app_id", <id>)
            .addToken("app_key", <ey>).setup();

        net.i2p.crypto.eddsa.KeyPairGenerator edDsaKpg = new net.i2p.crypto.eddsa.KeyPairGenerator();
        KeyPair keyPair = edDsaKpg.generateKeyPair();

        Map<String, Object> assetData = new HashMap<String, Object>() {{
            put("key", 1197.5864929752704);
        }};

        MetaData metaData = new MetaData();
        metaData.setMetaData("notes", "The CREATE transaction for a device asset");

        Transaction createTransaction = BigchainDbTransactionBuilder
            .init()
            .addAssets(assetData, HashMap.class)
            .addMetaData(metaData)
            .operation(Operations.CREATE)
            .buildAndSign((EdDSAPublicKey) keyPair.getPublic(), (EdDSAPrivateKey) keyPair.getPrivate())
            .sendTransaction(new GenericCallback() {
                @Override
                public void pushedSuccessfully(Response response) {

                }

                @Override
                public void transactionMalformed(Response response) {
                    handleError(response);
                }

                @Override
                public void otherError(Response response) {
                    handleError(response);
                }

                private void handleError(Response response) {
                    try {
                        System.out.println(new String(response.body().bytes()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            });
        System.out.println(createTransaction.getId());
    }
}

In output you should get message saying that signature is invalid
Tested with:

<dependency>
    <groupId>com.bigchaindb</groupId>
    <artifactId>bigchaindb-driver</artifactId>
    <version>1.1</version>
</dependency>

NPE in TransactionsApi.getTransactionById() if transaction does not exist

Driver version: 1.1 and master(cae61d8)
Response:
{"message":"Not found","status":404}
Stacktrace:

Exception in thread "main" java.lang.NullPointerException
at com.bigchaindb.json.strategy.TransactionDeserializer.deserialize(TransactionDeserializer.java:50)
at com.bigchaindb.json.strategy.TransactionDeserializer.deserialize(TransactionDeserializer.java:23)
at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
at com.google.gson.Gson.fromJson(Gson.java:888)
at com.google.gson.Gson.fromJson(Gson.java:853)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.google.gson.Gson.fromJson(Gson.java:774)
at com.bigchaindb.util.JsonUtils.fromJson(JsonUtils.java:133)
at com.bigchaindb.api.TransactionsApi.getTransactionById(TransactionsApi.java:74)

Transaction operation issue

In BigchainDbTransactionBuilder.build() method
instead of using:
if (this.transaction.getOperation() == null) // line 167
need to be
(this.operation == null)
Without this change this.transaction.getOperation() always null.

Transfer transaction returns Malformed Request Error

i am trying to run sample https://gist.github.com/innoprenuer/d4c6798fe5c0581c05a7e676e175e515

The asset creation working fine, however when i transferred asset, it returns
malformed BAD REQUEST
Transaction failed

I am unable to query (via HTTP API) the transaction ID as well, it throws 404 not found error;

Update:
It turns out, if i use BigchainDbTransactionBuilder like below,
Transaction transferTransaction = BigchainDbTransactionBuilder .init() .operation(Operations.TRANSFER) .addInput("FULLFILLMENT", spendFrom, (EdDSAPublicKey) alice.getPublic()) .addOutput("1", (EdDSAPublicKey) robert.getPublic()) .addAssets(aliceRegisterTx.getAsset().getData(), TreeMap.class) .addMetaData(transferMetadata) .buildAndSign((EdDSAPublicKey) alice.getPublic(), (EdDSAPrivateKey) alice.getPrivate()) .sendTransaction(handleServerResponse());

I notice that operation type is not detected, hence making it populated by default (CREATE), however i tried to create a manual version of transaction building (not using builder a.k.a copy paste the code in builder class) the output was set correctly (TRANSFER) but the main problem still linger.

I compared the json output after send transaction, and no invalid structure spotted

AssetsApi.getAssets(searchString) not working

Hi,
when I run a getAssets query manually it works. When I run it via the Java driver it fails with the following errors:

09-29 09:02:00.136: W/System.err(4511): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Not a JSON Array: ""
09-29 09:02:00.136: W/System.err(4511): at com.google.gson.Gson.fromJson(Gson.java:900)
09-29 09:02:00.136: W/System.err(4511): at com.google.gson.Gson.fromJson(Gson.java:853)
09-29 09:02:00.136: W/System.err(4511): at com.google.gson.Gson.fromJson(Gson.java:802)
09-29 09:02:00.136: W/System.err(4511): at com.google.gson.Gson.fromJson(Gson.java:774)
09-29 09:02:00.136: W/System.err(4511): at com.bigchaindb.util.JsonUtils.fromJson(JsonUtils.java:133)
09-29 09:02:00.136: W/System.err(4511): at com.bigchaindb.api.AssetsApi.getAssets(AssetsApi.java:37)

09-29 09:02:00.137: W/System.err(4511): Caused by: java.lang.IllegalStateException: Not a JSON Array: ""
09-29 09:02:00.137: W/System.err(4511): at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:107)
09-29 09:02:00.137: W/System.err(4511): at com.bigchaindb.json.strategy.AssetsDeserializer.deserialize(AssetsDeserializer.java:31)
09-29 09:02:00.137: W/System.err(4511): at com.bigchaindb.json.strategy.AssetsDeserializer.deserialize(AssetsDeserializer.java:21)
09-29 09:02:00.137: W/System.err(4511): at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
09-29 09:02:00.137: W/System.err(4511): at com.google.gson.Gson.fromJson(Gson.java:888)

The call I use is

AssetsApi.getAssets(searchString)

Thanks,

Alex

Add ability to get unspent transactions for the given asset

One of the easiest ways to add value in Java driver is to provide a method for querying unspent transactions for a given asset. This is a very common feature for any use case. So, it makes sense to provide this ability in the driver. Implementation can be to either use unspent_outputs api of bigchaindb server or write logic to optimally fetch unspent output in the driver itself. Currently, it makes sense to use api from the server itself as it is easier to implement and straight forward.

Invalid signature when sending TRANSFER transaction

It appears TRANSFER transactions still don't work via the Java driver. Although the schema seems to match the Python driver perfectly, for both CREATE and TRANSFER, only CREATE works. Digging into BigchainDB's mainline code, it seems like the failure happens here, in the transaction commons, during validation.

In my experiments with the Python driver, TRANSFER transactions worked fine. So there is something weird going on with Java. I try to build my transaction like so:

// prepare input
final FulFill sourceXfer = new FulFill();
sourceXfer.setTransactionId(createTxn.getId());
sourceXfer.setOutputIndex(0);

// build asset reference
final String assetId = createTxn.getId();

    // prepare a xfer transaction, and sign it
final BigchainDbTransactionBuilder.ITransactionAttributes attrs = BigchainDbTransactionBuilder
    .init()
    .addInput(null, sourceXfer, (EdDSAPublicKey) owner.getKeypair().getPublic())  // owner is the source identity
    .addOutput(amount, (EdDSAPublicKey) target.getKeypair().getPublic())  // target is the destination identity
    .addAssets(assetId, String.class)
    .operation(Operations.TRANSFER);

// attach metadata, if we have it
if (asset.getMetadata() != null)
  attrs.addMetaData(asset.getMetadata());

final Transaction txn = attrs.buildAndSignOnly(
    (EdDSAPublicKey) owner.getKeypair().getPublic(),
    (EdDSAPrivateKey) owner.getKeypair().getPrivate());

But, here is what I get from Bigchain in my docker-compose logs:

mongodb_1     | <timestamp> I NETWORK  [listener] connection accepted from x.x.x.x:yy #14 (10 connections now open)
mongodb_1     | <timestamp> I NETWORK  [conn14] received client metadata from x.x.x.x:yy conn14: { driver: { name: "PyMongo", version: "3.7.1" }, os: { type: "Linux", name: "Linux", architecture: "x86_64", version: "4.9.93-linuxkit-aufs" }, platform: "CPython 3.6.6.final.0" }

bigchaindb_1  | <timestamp> | [ERROR] (bigchaindb.web.views.base) HTTP API error: 400 - POST:/api/v1/transactions - Invalid transaction, could not validate (InvalidSignature): Transaction signature is invalid. (bigchaindb_webapi - pid: 31)

Most notably, of course, is the last line there, which says:
Invalid transaction, could not validate (InvalidSignature): Transaction signature is invalid.

This builds on the original bug filed by @NikitaLos (#2, Transaction operation issue).

Getting id of asset always null

When i invoke
Transaction lastTransaction = TransactionsApi.getTransactionById(id); - here i get not null trasaction
Asset asset = lastTransaction.getAsset() - here i get not null asset
asset.getId() - here i get null, but when i check asset id in mongo it is not null

Transfer Transaction does not generate a valid hash

When you create a transaction with Transfer Operation, a hash is generated which is also the transaction id.

This hash generated by the driver, and the hash generated by bigchain db are different.
This request was sent to test net.

Request

{"asset":{"data":"b7349b6c00e077d091959bd37b540289893e6b017838819ee13db92ed7cd1919"},"id":"65e85ce974716a5ed54e124ccf51605576b74cf86ed7c0bb09a812b863f382a2","inputs":[{"fulfillment":"pGSAIM4NkVLNF61l4_6SbQKiKPQJVFARrB3eha205VkB6v9CgUAMujcVmpGm2bDHO8iJDl-pNAP5w96tnUe4u_n4jyTefQMyjrF3b-paf5yQjL8yc8dJNPpP_YrOh3DDtX1-sZkA","fulfills":{"output_index":"0","transaction_id":"b7349b6c00e077d091959bd37b540289893e6b017838819ee13db92ed7cd1919"},"owners_before":["EsLz8izHvmisM4j4KUgcPvcenibzJrsykaW9VxcVjD3o"]}],"metadata":null,"operation":"TRANSFER","outputs":[{"amount":"1","condition":{"details":{"public_key":"AxbvZ3xLPvA4A4raqLd2Xq5MG1KgxY2VKg2rMjiBzyPA","type":"ed25519-sha-256"},"uri":"ni:///sha-256;dSlYz671P2vCftHOtSnk1xKk0X-XCMqVosBPIGXcCgc?fpt=ed25519-sha-256&cost=131072"},"public_keys":["AxbvZ3xLPvA4A4raqLd2Xq5MG1KgxY2VKg2rMjiBzyPA"]}],"version":"2.0"}

Response:

{
    "message": "Invalid transaction (InvalidHash): The transaction's id '65e85ce974716a5ed54e124ccf51605576b74cf86ed7c0bb09a812b863f382a2' isn't equal to the hash of its body, i.e. it's not valid.",
    "status": 400
}

But create transaction works as expected without issues. Is it possible that something is wrong with the request, but BigchainDB sends a wrong/misleading error message?

CREATE -> TRANSFER -> TRANSFER throws 400

To reproduce this issue, perform below operations

  1. CREATE
  2. TRANSFER of (1)
  3. TRANSFER of (2)

When performing operation (3), metadata object is serialized with value {} which is not valid schema for transaction on BigchainDB server, and hence server throws HTTP 400 Invalid schema {}

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.