├── .gitignore ├── .travis.yml ├── CONTRIBUTING.rst ├── LICENSE ├── LICENSE-docs ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── media ├── repo-banner.sketch └── repo-banner@2x.png ├── pom.xml ├── settings.gradle └── src ├── main └── java │ ├── META-INF │ └── MANIFEST.MF │ └── com │ └── bigchaindb │ ├── annotations │ └── Exclude.java │ ├── api │ ├── AbstractApi.java │ ├── AccountApi.java │ ├── AssetsApi.java │ ├── BlocksApi.java │ ├── MetaDataApi.java │ ├── OutputsApi.java │ ├── TransactionsApi.java │ └── ValidatorsApi.java │ ├── builders │ ├── BigchainDbConfigBuilder.java │ └── BigchainDbTransactionBuilder.java │ ├── constants │ ├── BigchainDbApi.java │ └── Operations.java │ ├── exceptions │ └── TransactionNotFoundException.java │ ├── json │ ├── factory │ │ └── GsonEmptyCheckTypeAdapterFactory.java │ └── strategy │ │ ├── AssetSerializer.java │ │ ├── AssetsDeserializer.java │ │ ├── CustomExclusionStrategy.java │ │ ├── InputSerializer.java │ │ ├── MetaDataDeserializer.java │ │ ├── MetaDataSerializer.java │ │ ├── OutputsDeserializer.java │ │ ├── TransactionDeserializer.java │ │ ├── TransactionIdExclusionStrategy.java │ │ ├── TransactionsDeserializer.java │ │ └── ValidatorDeserializer.java │ ├── model │ ├── Account.java │ ├── ApiEndpoints.java │ ├── Asset.java │ ├── Assets.java │ ├── BigChainDBGlobals.java │ ├── Block.java │ ├── Condition.java │ ├── Connection.java │ ├── DataModel.java │ ├── Details.java │ ├── FulFill.java │ ├── GenericCallback.java │ ├── Input.java │ ├── MetaData.java │ ├── MetaDatas.java │ ├── Output.java │ ├── Outputs.java │ ├── Transaction.java │ ├── Transactions.java │ ├── ValidTransaction.java │ ├── Validator.java │ ├── ValidatorPubKey.java │ └── Validators.java │ ├── util │ ├── Base58.java │ ├── DriverUtils.java │ ├── JsonUtils.java │ ├── KeyPairUtils.java │ ├── NetworkUtils.java │ ├── ScannerUtil.java │ └── TypeAdapter.java │ └── ws │ ├── BigchainDbWSSessionManager.java │ └── MessageHandler.java └── test ├── java └── com │ └── bigchaindb │ ├── AbstractTest.java │ ├── api │ ├── AbstractApiTest.java │ ├── AccountApiTest.java │ ├── AssetsApiTest.java │ ├── BlocksApiTest.java │ ├── MetaDataApiTest.java │ ├── OutputsApiTest.java │ ├── TransactionCreateApiTest.java │ ├── TransactionTransferApiTest.java │ └── ValidatorsApiTest.java │ ├── builders │ └── BigchainDBConnectionManagerTest.java │ ├── keys │ ├── PrivateKeyTest.java │ └── PublicKeyTest.java │ ├── util │ ├── KeyPairUtilsTest.java │ └── ScannerUtilsTest.java │ └── ws │ ├── ValidTransactionMessageHandler.java │ └── WsMonitorTest.java └── resources ├── log4j.properties └── test.properties /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle specific .gitignore, see https://github.com/github/gitignore/blob/master/Gradle.gitignore 2 | .gradle 3 | /build/ 4 | 5 | # Ignore Gradle GUI config 6 | gradle-app.setting 7 | 8 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 9 | !gradle-wrapper.jar 10 | 11 | # Cache of project 12 | .gradletasknamecache 13 | 14 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 15 | # gradle/wrapper/gradle-wrapper.properties 16 | 17 | # IntelliJ specific files 18 | .idea 19 | *.iml 20 | out 21 | 22 | 23 | # Maven 24 | target/ 25 | 26 | # Eclipse specific 27 | .classpath 28 | .project 29 | .settings/ 30 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Copyright BigchainDB GmbH and BigchainDB contributors 2 | # SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 3 | # Code is Apache-2.0 and docs are CC-BY-4.0 4 | 5 | language: java 6 | sudo: required 7 | jdk: 8 | - oraclejdk8 9 | install: true 10 | 11 | services: 12 | - docker 13 | 14 | install: 15 | - docker pull bigchaindb/bigchaindb 16 | - docker run --interactive --rm --tty --volume $HOME/bigchaindb_docker:/data --env BIGCHAINDB_DATABASE_HOST=172.17.0.1 bigchaindb/bigchaindb -y configure localmongodb 17 | - docker run --detach --name=mongodb --publish=27017:27017 --restart=always --volume=$HOME/mongodb_docker/db:/data/db --volume=$HOME/mongodb_docker/configdb:/data/configdb mongo:3.4.9 --replSet=bigchain-rs 18 | - docker run --detach --name=bigchaindb --publish=9984:9984 --restart=always --volume=$HOME/bigchaindb_docker:/data bigchaindb/bigchaindb start 19 | 20 | #before_script: 21 | # - mvn install:install-file -Dfile=$TRAVIS_BUILD_DIR/libs/java-crypto-conditions-2.0.0-SNAPSHOT.jar -DgroupId=org.interledger -DartifactId=java-crypto-conditions -Dversion=2.0.0-SNAPSHOT -Dpackaging=jar 22 | 23 | cache: 24 | directories: 25 | - $HOME/.m2 26 | 27 | branches: 28 | only: 29 | - master 30 | 31 | script: 32 | - mvn clean install 33 | - ./gradlew clean install 34 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | 2 | .. Copyright BigchainDB GmbH and BigchainDB contributors 3 | SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | Code is Apache-2.0 and docs are CC-BY-4.0 5 | 6 | .. highlight:: shell 7 | 8 | ============ 9 | Contributing 10 | ============ 11 | 12 | Contributions are welcome, and they are greatly appreciated! Every 13 | little bit helps, and credit will always be given. 14 | 15 | You can contribute in many ways: 16 | 17 | Types of Contributions 18 | ---------------------- 19 | 20 | Report Bugs 21 | ~~~~~~~~~~~ 22 | 23 | Report bugs at https://github.com/bigchaindb/java-bigchaindb-driver/issues. 24 | 25 | If you are reporting a bug, please include: 26 | 27 | * Your operating system name and version. 28 | * Any details about your local setup that might be helpful in troubleshooting. 29 | * Detailed steps to reproduce the bug. 30 | 31 | Fix Bugs 32 | ~~~~~~~~ 33 | 34 | Look through the GitHub issues for bugs. Anything tagged with "bug" 35 | and "help wanted" is open to whoever wants to implement it. 36 | 37 | Implement Features 38 | ~~~~~~~~~~~~~~~~~~ 39 | 40 | Look through the GitHub issues for features. Anything tagged with "enhancement" 41 | and "help wanted" is open to whoever wants to implement it. 42 | 43 | Write Documentation 44 | ~~~~~~~~~~~~~~~~~~~ 45 | 46 | bigchaindb-driver could always use more documentation, whether as part of the 47 | official bigchaindb-driver docs, in docstrings, or even on the web in blog posts, 48 | articles, and such. 49 | 50 | Submit Feedback 51 | ~~~~~~~~~~~~~~~ 52 | 53 | The best way to send feedback is to file an issue at https://github.com/bigchaindb/java-bigchaindb-driver/issues. 54 | 55 | If you are proposing a feature: 56 | 57 | * Explain in detail how it would work. 58 | * Keep the scope as narrow as possible, to make it easier to implement. 59 | * Remember that this is a volunteer-driven project, and that contributions 60 | are welcome :) 61 | 62 | Get Started! 63 | ------------ 64 | 65 | Ready to contribute? Here's how to set up `java-bigchaindb-driver`_ for local 66 | development. 67 | 68 | 1. Fork the `java-bigchaindb-driver`_ repo on GitHub. 69 | 2. Clone your fork locally and enter into the project:: 70 | 71 | $ git clone git@github.com:your_name_here/java-bigchaindb-driver.git 72 | $ cd java-bigchaindb-driver/ 73 | 74 | 3. Create a branch for local development:: 75 | 76 | $ git checkout -b name-of-your-bugfix-or-feature 77 | 78 | Now you can make your changes locally. 79 | 80 | 4. Write tests ;-) 81 | 82 | 5. Test! 83 | 84 | 6. Commit your changes and push your branch to GitHub:: 85 | 86 | $ git add . 87 | $ git commit -m "Your detailed description of your changes." 88 | $ git push origin name-of-your-bugfix-or-feature 89 | 90 | 7. Submit a pull request through the GitHub website. 91 | 92 | 93 | Pull Request Guidelines 94 | ----------------------- 95 | 96 | Before you submit a pull request, check that it meets these guidelines: 97 | 98 | 1. The pull request should include tests. 99 | 2. If the pull request adds functionality, the docs should be updated. Put 100 | your new functionality into a function with a docstring, and add the 101 | feature to the list in README.rst. 102 | 3. The pull request should work for JS and node. Travis or others would be an interesting 103 | way for automate the tests... 104 | 105 | 106 | Dependency on Bigchaindb 107 | ~~~~~~~~~~~~~~~~~~~~~~~~ 108 | 109 | This version is compatible from BigchainDB server v1.00 110 | 111 | .. _bigchaindb-driver: https://github.com/bigchaindb/java-bigchaindb-driver 112 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | -------------------------------------------------------------------------------- /LICENSE-docs: -------------------------------------------------------------------------------- 1 | The official BigchainDB documentation, 2 | except for the short code snippets embedded within it, 3 | is licensed under a Creative Commons Attribution-ShareAlike 4.0 International license, 4 | the full text of which can be found 5 | at http://creativecommons.org/licenses/by-sa/4.0/legalcode 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | [![Build Status](https://travis-ci.com/bigchaindb/java-bigchaindb-driver.svg?branch=master)](https://travis-ci.com/bigchaindb/java-bigchaindb-driver) 8 | [![Gitter](http://badges.gitter.im/bigchaindb/bigchaindb.svg)](https://gitter.im/bigchaindb/bigchaindb) 9 | [![java-bigchaindb-driver](media/repo-banner@2x.png)](https://www.bigchaindb.com) 10 | 11 | # Official Java and Android Driver for BigchainDB 12 | 13 | **Please note**: This driver is compatible with Android API 23 and later. 14 | 15 | ## Compatibility 16 | 17 | | BigchainDB Server | BigchainDB Java Driver | 18 | | ----------------- |------------------------------| 19 | | `2.x` | `1.x` | 20 | 21 | ## Contents 22 | 23 | * [Installation](#installation) 24 | * [Usage](#usage) 25 | * [API Wrappers](#api-wrappers) 26 | * [BigchainDB Documentation](#bigchaindb-documentation) 27 | * [Authors](#authors) 28 | * [Licenses](#licenses) 29 | 30 | ## Installation 31 | 32 | The build system supports both Maven and Gradle. 33 | 34 | ### Maven Users 35 | 36 | In your `pom.xml` file, add `bigchaindb-driver` as a dependency: 37 | 38 | ```xml 39 | 40 | com.bigchaindb 41 | bigchaindb-driver 42 | 1.0 43 | 44 | ``` 45 | 46 | then 47 | 48 | ``` 49 | mvn clean install 50 | ``` 51 | 52 | ### Gradle Users 53 | 54 | In your `build.gradle` file, add `bigchaindb-driver` as a dependency: 55 | 56 | ``` 57 | dependencies { 58 | implementation 'com.bigchaindb.bigchaindb-driver:1.2' 59 | } 60 | ``` 61 | 62 | then 63 | 64 | ``` 65 | ./gradlew install 66 | ``` 67 | 68 | ## Usage 69 | 70 | > A sample of an end-to-end CREATE and TRANSFER operation is available in the gist [https://gist.github.com/innoprenuer/d4c6798fe5c0581c05a7e676e175e515](https://gist.github.com/innoprenuer/d4c6798fe5c0581c05a7e676e175e515) 71 | 72 | ### Set Up Your Configuration 73 | 74 | #### Single-Node Setup 75 | 76 | ```java 77 | BigchainDbConfigBuilder 78 | .baseUrl("https://node1.example.com/") 79 | .addToken("header1", ) 80 | .addToken("header2", ).setup(); 81 | ``` 82 | 83 | #### Multi-Node Setup (More Robust and Reliable) 84 | 85 | > **Note** - multi-node setup is only available in version 1.2 and later 86 | > 87 | > **Assumption** - The following setup assumes that all nodes are all connected within same BigchainDB network. 88 | 89 | ```java 90 | //define connections 91 | Map conn1Config = new HashMap(), 92 | conn2Config = new HashMap(); 93 | 94 | //define headers for connections 95 | Map headers1 = new HashMap(); 96 | Map headers2 = new HashMap(); 97 | 98 | //config header for connection 1 99 | headers1.put("app_id", ""); 100 | headers1.put("app_key", ""); 101 | 102 | //config header for connection 2 103 | headers2.put("app_id", ""); 104 | headers2.put("app_key", ""); 105 | 106 | //config connection 1 107 | conn1Config.put("baseUrl", "https://node1.mysite.com/"); 108 | conn1Config.put("headers", headers1); 109 | Connection conn1 = new Connection(conn1Config); 110 | 111 | //config connection 2 112 | conn2Config.put("baseUrl", "https://node2.mysite.com/"); 113 | conn2Config.put("headers", headers2); 114 | Connection conn2 = new Connection(conn2Config); 115 | 116 | //add connections 117 | List connections = new ArrayList(); 118 | connections.add(conn1); 119 | connections.add(conn2); 120 | //...You can add as many nodes as you want 121 | 122 | BigchainDbConfigBuilder 123 | .addConnections(connections) 124 | .setTimeout(60000) //override default timeout of 20000 milliseconds 125 | .setup(); 126 | 127 | } 128 | ``` 129 | 130 | ### Example: Prepare Keys, Assets and Metadata 131 | 132 | ```java 133 | // prepare your keys 134 | net.i2p.crypto.eddsa.KeyPairGenerator edDsaKpg = new net.i2p.crypto.eddsa.KeyPairGenerator(); 135 | KeyPair keyPair = edDsaKpg.generateKeyPair(); 136 | 137 | // New asset 138 | Map assetData = new TreeMap() {{ 139 | put("city", "Berlin, DE"); 140 | put("temperature", "22"); 141 | put("datetime", new Date().toString()); 142 | }}; 143 | 144 | // New metadata 145 | MetaData metaData = new MetaData(); 146 | metaData.setMetaData("what", "My first BigchainDB transaction"); 147 | ``` 148 | 149 | ### Example: Create an Asset 150 | 151 | Performing a CREATE transaction in BigchainDB allocates or issues a digital asset. 152 | 153 | ```java 154 | // Set up, sign, and send your transaction 155 | Transaction createTransaction = BigchainDbTransactionBuilder 156 | .init() 157 | .addAssets(assetData, TreeMap.class) 158 | .addMetaData(metaData) 159 | .operation(Operations.CREATE) 160 | .buildAndSign((EdDSAPublicKey) keyPair.getPublic(), (EdDSAPrivateKey) keyPair.getPrivate()) 161 | .sendTransaction(); 162 | ``` 163 | 164 | ### Example: Transfer an Asset 165 | 166 | Performing a TRANSFER transaction in BigchainDB changes an asset's ownership (or, more accurately, authorized signers): 167 | 168 | ```java 169 | // Generate a new keypair to TRANSFER the asset to 170 | KeyPair targetKeypair = edDsaKpg.generateKeyPair(); 171 | 172 | // Describe the output you are fulfilling on the previous transaction 173 | final FulFill spendFrom = new FulFill(); 174 | spendFrom.setTransactionId(createTransaction.getId()); 175 | spendFrom.setOutputIndex(0); 176 | 177 | // Change the metadata if you want 178 | MetaData transferMetadata = new MetaData(); 179 | metaData.setMetaData("what2", "My first BigchainDB transaction"); 180 | 181 | // the asset's ID is equal to the ID of the transaction that created it 182 | String assetId = createTransaction.getId(); 183 | 184 | // By default, the 'amount' of a created digital asset == "1". So we spend "1" in our TRANSFER. 185 | String amount = "1"; 186 | 187 | // Use the previous transaction's asset and TRANSFER it 188 | Transaction transferTransaction = BigchainDbTransactionBuilder 189 | .init() 190 | .addMetaData(metaData) 191 | 192 | // source keypair is used in the input, because the current owner is "spending" the output to transfer it 193 | .addInput(null, spendFrom, (EdDSAPublicKey) keyPair.getPublic()) 194 | 195 | // after this transaction, the target 'owns' the asset, so, the new output includes the target's public key 196 | .addOutput(output, (EdDSAPublicKey) targetKeypair.getPublic()) 197 | 198 | // reference the asset by ID when doing a transfer 199 | .addAssets(assetId, String.class) 200 | .operation(Operations.TRANSFER) 201 | 202 | // the source key signs the transaction to authorize the transfer 203 | .buildAndSign((EdDSAPublicKey) keyPair.getPublic(), (EdDSAPrivateKey) keyPair.getPrivate()) 204 | .sendTransaction(); 205 | ``` 206 | 207 | ### Example: Setup Config with WebSocket Listener 208 | 209 | ```java 210 | public class MyCustomMonitor implements MessageHandler { 211 | @Override 212 | public void handleMessage(String message) { 213 | ValidTransaction validTransaction = JsonUtils.fromJson(message, ValidTransaction.class); 214 | } 215 | } 216 | 217 | // config 218 | BigchainDbConfigBuilder 219 | .baseUrl("https://api.example.net") 220 | .addToken("app_id", "2bbaf3ff") 221 | .addToken("app_key", "c929b708177dcc8b9d58180082029b8d") 222 | .webSocketMonitor(new MyCustomMonitor()) 223 | .setup(); 224 | ``` 225 | 226 | ### More Examples 227 | 228 | #### Example: Create a Transaction (without signing and without sending) 229 | 230 | ```java 231 | // Set up your transaction but only build it 232 | Transaction transaction = BigchainDbTransactionBuilder 233 | .init() 234 | .addAssets(assetData, TreeMap.class) 235 | .addMetaData(metaData) 236 | .operation(Operations.CREATE) 237 | .buildOnly((EdDSAPublicKey) keyPair.getPublic()); 238 | ``` 239 | 240 | #### Example: Create and Sign Transaction (without sending it to the ledger) 241 | 242 | ```java 243 | // Set up your transaction 244 | Transaction transaction = BigchainDbTransactionBuilder 245 | .init() 246 | .addAssets(assetData, TreeMap.class) 247 | .addMetaData(metaData) 248 | .operation(Operations.CREATE) 249 | .buildAndSignOnly((EdDSAPublicKey) keyPair.getPublic(), (EdDSAPrivateKey) keyPair.getPrivate()); 250 | ``` 251 | 252 | ## API Wrappers 253 | 254 | ### Transactions 255 | 256 | #### Send a Transaction 257 | 258 | ```java 259 | TransactionsApi.sendTransaction(Transaction transaction) throws IOException 260 | ``` 261 | 262 | #### Send a Transaction with Callback 263 | 264 | ```java 265 | TransactionsApi.sendTransaction(Transaction transaction, final GenericCallback callback) 266 | ``` 267 | 268 | #### Get Transaction given a Transaction Id 269 | 270 | ```java 271 | Transaction TransactionsApi.getTransactionById(String id) throws IOException 272 | ``` 273 | 274 | #### Get Transaction given an Asset Id 275 | 276 | ```java 277 | Transactions TransactionsApi.getTransactionsByAssetId(String assetId, Operations operation) 278 | ``` 279 | 280 | ### Outputs 281 | 282 | #### Get Outputs given a public key 283 | 284 | ```java 285 | Outputs getOutputs(String publicKey) throws IOException 286 | ``` 287 | 288 | #### Get Spent Outputs given a public key 289 | 290 | ```java 291 | Outputs getSpentOutputs(String publicKey) throws IOException 292 | ``` 293 | 294 | #### Get Unspent Outputs given a public key 295 | 296 | ```java 297 | Outputs getUnspentOutputs(String publicKey) throws IOException 298 | ``` 299 | 300 | ### Assets 301 | 302 | #### Get Assets given search key 303 | 304 | ```java 305 | Assets getAssets(String searchKey) throws IOException 306 | ``` 307 | 308 | #### Get Assets given search key and limit 309 | 310 | ```java 311 | Assets getAssetsWithLimit(String searchKey, String limit) throws IOException 312 | ``` 313 | 314 | ### Blocks 315 | 316 | #### Get Blocks given block id 317 | 318 | ```java 319 | Block getBlock(String blockId) throws IOException 320 | ``` 321 | 322 | #### Get Blocks given transaction id 323 | 324 | ```java 325 | List getBlocksByTransactionId(String transactionId) throws IOException 326 | ``` 327 | 328 | ### MetaData 329 | 330 | #### Get MetaData given search key 331 | 332 | ```java 333 | MetaDatas getMetaData(String searchKey) throws IOException 334 | ``` 335 | 336 | #### Get MetaData given search key and limit 337 | 338 | ```java 339 | MetaDatas getMetaDataWithLimit(String searchKey, String limit) throws IOException 340 | ``` 341 | 342 | ### Validators 343 | 344 | #### Gets the the local validators set of a given node 345 | 346 | ```java 347 | Validators getValidators() throws IOException 348 | ``` 349 | 350 | ## BigchainDB Documentation 351 | 352 | * [HTTP API Reference](https://docs.bigchaindb.com/projects/server/en/latest/http-client-server-api.html) 353 | * [The Transaction Model](https://docs.bigchaindb.com/projects/server/en/latest/metadata-models/transaction-model.html?highlight=crypto%20conditions) 354 | * [Inputs and Outputs](https://docs.bigchaindb.com/projects/server/en/latest/metadata-models/inputs-outputs.html) 355 | * [Asset Transfer](https://docs.bigchaindb.com/projects/py-driver/en/latest/usage.html#asset-transfer) 356 | * [All BigchainDB Documentation](https://docs.bigchaindb.com/) 357 | 358 | ## Authors 359 | 360 | Inspired by [http://github.com/authenteq/java-bigchaindb-driver](http://github.com/authenteq/java-bigchaindb-driver). 361 | 362 | The [BigchainDB](https://bigchaindb.com) team and others including: 363 | 364 | * @bodia 365 | * @alvin-reyes 366 | * @agwego 367 | * @nf-PostQuantum 368 | * @Rokko11 369 | * @tzclucian 370 | * @kremalicious 371 | * @avanaur 372 | * @GerardoGa 373 | * @bakaoh 374 | * @innoprenuer 375 | 376 | ## Release Process 377 | 378 | To execute a release build with Maven, define `performRelease` to enable GPG signing: 379 | 380 | `mvn clean package install -DperformRelease` 381 | 382 | ## Licenses 383 | 384 | See [LICENSE](LICENSE) and [LICENSE-docs](LICENSE-docs). 385 | 386 | 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. 387 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'eclipse' 3 | apply plugin: 'maven' 4 | apply plugin: 'checkstyle' 5 | 6 | targetCompatibility = 1.8 7 | sourceCompatibility = 1.8 8 | 9 | group = 'com.bigchaindb' 10 | version = '0.1' 11 | description = 'Java Driver for Bigchaindb' 12 | 13 | jar { 14 | manifest { 15 | attributes 'Implementation-Title': description, 16 | 'Implementation-Version': version, 17 | 'Main-Class': 'com.bigchaindb.Main' 18 | } 19 | } 20 | 21 | repositories { 22 | maven { url "http://repo.maven.apache.org/maven2" } 23 | mavenLocal() 24 | } 25 | 26 | dependencies { 27 | compile 'com.squareup.okhttp3:okhttp:3.9.0' 28 | compile 'net.i2p.crypto:eddsa:0.2.0' 29 | compile 'commons-codec:commons-codec:1.10' 30 | compile 'com.google.code.gson:gson:2.8.2' 31 | compile 'org.slf4j:slf4j-api:1.7.25' 32 | compile 'com.bigchaindb:cryptoconditions:1.0' 33 | compile 'org.bouncycastle:bcprov-jdk15on:1.54' 34 | compile 'org.glassfish.tyrus.bundles:tyrus-standalone-client:1.9' 35 | 36 | testCompile 'junit:junit:4.12' 37 | testCompile 'org.apache.logging.log4j:log4j-core:2.9.1' 38 | testCompile 'org.slf4j:slf4j-log4j12:1.7.25' 39 | testCompile group: 'net.jadler', name: 'jadler-all', version: '1.3.0' 40 | 41 | } 42 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigchaindb/java-bigchaindb-driver/54372a3d29eef5ce43cf5e76ab4b879fb616a8a3/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jul 28 23:55:35 SAST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /media/repo-banner.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigchaindb/java-bigchaindb-driver/54372a3d29eef5ce43cf5e76ab4b879fb616a8a3/media/repo-banner.sketch -------------------------------------------------------------------------------- /media/repo-banner@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bigchaindb/java-bigchaindb-driver/54372a3d29eef5ce43cf5e76ab4b879fb616a8a3/media/repo-banner@2x.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | com.bigchaindb 8 | bigchaindb-driver 9 | 1.2 10 | jar 11 | 12 | bigchaindb-driver 13 | Official Java driver for bigchaindb 14 | http://github.com/bigchaindb/java-bigchaindb-driver 15 | 16 | 17 | 18 | The Apache Software License, Version 2.0 19 | http://www.apache.org/licenses/LICENSE-2.0.txt 20 | repo 21 | 22 | 23 | 24 | 25 | 26 | Manan Patel 27 | manan@bigchaindb.com 28 | Bigchaindb 29 | http://www.bigchaindb.com 30 | 31 | 32 | 33 | 34 | scm:git:git://github.com/bigchaindb/java-crypto-conditions.git 35 | scm:git:ssh://github.com:bigchaindb/java-crypto-conditions.git 36 | http://github.com/bigchaindb/java-crypto-conditions/tree/master 37 | 38 | 39 | 40 | true 41 | 1.8 42 | UTF-8 43 | 1.8 44 | 45 | 46 | 47 | 48 | release-sign-artifacts 49 | 50 | 51 | performRelease 52 | true 53 | 54 | 55 | 56 | 57 | 58 | org.apache.maven.plugins 59 | maven-gpg-plugin 60 | 1.6 61 | 62 | 63 | sign-artifacts 64 | verify 65 | 66 | sign 67 | 68 | 69 | 70 | --pinentry-mode 71 | loopback 72 | 73 | ${gpg.keyname} 74 | ${gpg.keyname} 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | maven-assembly-plugin 88 | 89 | 90 | package 91 | 92 | single 93 | 94 | 95 | 96 | 97 | 98 | jar-with-dependencies 99 | 100 | 101 | 102 | 103 | org.apache.maven.plugins 104 | maven-compiler-plugin 105 | 3.6.2 106 | 107 | 1.8 108 | 1.8 109 | 110 | 111 | 112 | org.apache.maven.plugins 113 | maven-source-plugin 114 | 2.2.1 115 | 116 | 117 | attach-sources 118 | 119 | jar-no-fork 120 | 121 | 122 | 123 | 124 | 125 | org.apache.maven.plugins 126 | maven-javadoc-plugin 127 | 128 | 129 | attach-javadocs 130 | 131 | jar 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | com.squareup.okhttp3 142 | okhttp 143 | 3.9.0 144 | 145 | 146 | net.i2p.crypto 147 | eddsa 148 | 0.2.0 149 | 150 | 151 | com.google.api-client 152 | google-api-client 153 | 1.23.0 154 | 155 | 156 | commons-codec 157 | commons-codec 158 | 1.10 159 | test 160 | 161 | 162 | com.google.code.gson 163 | gson 164 | 2.8.2 165 | 166 | 167 | 168 | org.slf4j 169 | slf4j-api 170 | 1.7.25 171 | 172 | 173 | 174 | org.apache.logging.log4j 175 | log4j-core 176 | 2.9.1 177 | test 178 | 179 | 180 | 181 | org.slf4j 182 | slf4j-log4j12 183 | 1.7.25 184 | test 185 | 186 | 187 | 188 | com.bigchaindb 189 | cryptoconditions 190 | 1.0 191 | 192 | 193 | org.bouncycastle 194 | bcprov-jdk15on 195 | 1.54 196 | 197 | 198 | junit 199 | junit 200 | 4.12 201 | test 202 | 203 | 204 | org.glassfish.tyrus.bundles 205 | tyrus-standalone-client 206 | 1.9 207 | 208 | 209 | net.jadler 210 | jadler-all 211 | 1.3.0 212 | test 213 | 214 | 215 | 216 | 217 | 218 | 219 | oss.sonatype.org 220 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 221 | 222 | 223 | oss.sonatype.org 224 | https://oss.sonatype.org/content/repositories/snapshots 225 | 226 | 227 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'java-bigchaindb-driver' 2 | -------------------------------------------------------------------------------- /src/main/java/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: com.bigchaindb.Main 3 | 4 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/annotations/Exclude.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.annotations; 7 | 8 | import java.lang.annotation.ElementType; 9 | import java.lang.annotation.Retention; 10 | import java.lang.annotation.RetentionPolicy; 11 | import java.lang.annotation.Target; 12 | 13 | /** 14 | * The Interface Exclude. 15 | */ 16 | @Retention(RetentionPolicy.RUNTIME) 17 | @Target({ElementType.FIELD}) 18 | public @interface Exclude { 19 | 20 | } -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/api/AbstractApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | import okhttp3.MediaType; 8 | 9 | 10 | 11 | /** 12 | * The Class AbstractApi. 13 | */ 14 | public abstract class AbstractApi { 15 | 16 | 17 | /** The Constant JSON. */ 18 | protected static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/api/AccountApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import java.security.KeyPair; 9 | import java.security.PrivateKey; 10 | import java.security.PublicKey; 11 | import java.security.spec.InvalidKeySpecException; 12 | import java.security.spec.PKCS8EncodedKeySpec; 13 | import java.security.spec.X509EncodedKeySpec; 14 | 15 | import net.i2p.crypto.eddsa.EdDSAPrivateKey; 16 | import net.i2p.crypto.eddsa.EdDSAPublicKey; 17 | import net.i2p.crypto.eddsa.Utils; 18 | import org.slf4j.LoggerFactory; 19 | 20 | import com.bigchaindb.model.Account; 21 | 22 | /** 23 | * The Class AccountApi. 24 | */ 25 | public class AccountApi extends AbstractApi { 26 | 27 | private static final org.slf4j.Logger log = LoggerFactory.getLogger( AccountApi.class ); 28 | 29 | /** 30 | * Creates the account. 31 | * 32 | * @return the account 33 | */ 34 | public static Account createAccount() { 35 | log.debug( "createAccount Call" ); 36 | Account newAccount = new Account(); 37 | net.i2p.crypto.eddsa.KeyPairGenerator edDsaKpg = new net.i2p.crypto.eddsa.KeyPairGenerator(); 38 | KeyPair keyPair = edDsaKpg.generateKeyPair(); 39 | newAccount.setPrivateKey(keyPair.getPrivate()); 40 | newAccount.setPublicKey(keyPair.getPublic()); 41 | log.debug( "createAccount Call : " + newAccount.getPublicKey().toString() ); 42 | return newAccount; 43 | } 44 | 45 | /** 46 | * Load account. 47 | * 48 | * @param publicKey 49 | * the public key 50 | * @param privateKey 51 | * the private key 52 | * @return the account 53 | * @throws InvalidKeySpecException 54 | * the invalid key spec exception 55 | */ 56 | public static Account loadAccount(String publicKey, String privateKey) throws InvalidKeySpecException { 57 | log.debug( "loadAccount Call" ); 58 | Account newAccount = new Account(); 59 | 60 | final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Utils.hexToBytes(publicKey)); 61 | final PublicKey pubKey = new EdDSAPublicKey(pubKeySpec); 62 | 63 | final PKCS8EncodedKeySpec encoded = new PKCS8EncodedKeySpec(Utils.hexToBytes(privateKey)); 64 | final PrivateKey privKey = new EdDSAPrivateKey(encoded); 65 | 66 | KeyPair keyPair = new KeyPair(pubKey, privKey); 67 | newAccount.setPrivateKey(keyPair.getPrivate()); 68 | newAccount.setPublicKey(keyPair.getPublic()); 69 | log.debug( "loadAccount Call : " + newAccount.getPublicKey().toString() ); 70 | return newAccount; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/api/AssetsApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import com.bigchaindb.constants.BigchainDbApi; 9 | import com.bigchaindb.model.Assets; 10 | import com.bigchaindb.model.BigChainDBGlobals; 11 | import com.bigchaindb.util.JsonUtils; 12 | import com.bigchaindb.util.NetworkUtils; 13 | 14 | import okhttp3.Response; 15 | import org.slf4j.LoggerFactory; 16 | 17 | import java.io.IOException; 18 | 19 | /** 20 | * The Class AssetsApi. 21 | */ 22 | public class AssetsApi { 23 | 24 | private static final org.slf4j.Logger log = LoggerFactory.getLogger( AssetsApi.class ); 25 | /** 26 | * Gets the assets. 27 | * 28 | * @param searchKey the search key 29 | * @return the assets 30 | * @throws IOException Signals that an I/O exception has occurred. 31 | */ 32 | public static Assets getAssets(String searchKey) throws IOException { 33 | log.debug( "getAssets Call :" + searchKey ); 34 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.ASSETS + "/?search="+ searchKey); 35 | String body = response.body().string(); 36 | response.close(); 37 | return JsonUtils.fromJson(body, Assets.class); 38 | } 39 | 40 | /** 41 | * Gets the assets with limit. 42 | * 43 | * @param searchKey the search key 44 | * @param limit the limit 45 | * @return the assets with limit 46 | * @throws IOException Signals that an I/O exception has occurred. 47 | */ 48 | public static Assets getAssetsWithLimit(String searchKey, String limit) throws IOException { 49 | log.debug( "getAssetsWithLimit Call :" + searchKey + " limit " + limit ); 50 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.ASSETS + "/?search="+ searchKey+ "&limit=" + limit); 51 | String body = response.body().string(); 52 | response.close(); 53 | return JsonUtils.fromJson(body, Assets.class); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/api/BlocksApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import com.bigchaindb.constants.BigchainDbApi; 9 | import com.bigchaindb.model.BigChainDBGlobals; 10 | import com.bigchaindb.model.Block; 11 | import com.bigchaindb.util.JsonUtils; 12 | import com.bigchaindb.util.NetworkUtils; 13 | import com.google.gson.reflect.TypeToken; 14 | import okhttp3.Response; 15 | import org.slf4j.LoggerFactory; 16 | 17 | import java.io.IOException; 18 | import java.util.List; 19 | 20 | 21 | /** 22 | * The Class BlocksApi. 23 | */ 24 | public class BlocksApi { 25 | 26 | private static final org.slf4j.Logger log = LoggerFactory.getLogger(BlocksApi.class); 27 | 28 | /** 29 | * Gets the block. 30 | * 31 | * @param blockId the block id 32 | * @return the block 33 | * @throws IOException Signals that an I/O exception has occurred. 34 | */ 35 | public static Block getBlock(String blockId) throws IOException { 36 | log.debug("getBlock Call :" + blockId); 37 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.BLOCKS + "/" + blockId); 38 | String body = response.body().string(); 39 | response.close(); 40 | return JsonUtils.fromJson(body, Block.class); 41 | } 42 | 43 | /** 44 | * Gets a list of block ids that contain the transaction 45 | * 46 | * @param transactionId the transaction id 47 | * @return the block ids 48 | * @throws IOException Signals that an I/O exception has occurred. 49 | */ 50 | public static List getBlocksByTransactionId(String transactionId) throws IOException { 51 | log.debug("getBlocks Call :" + transactionId); 52 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.BLOCKS + "?transaction_id=" + transactionId); 53 | String body = response.body().string(); 54 | response.close(); 55 | return JsonUtils.getGson().fromJson(body, new TypeToken>() { 56 | }.getType()); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/api/MetaDataApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import com.bigchaindb.constants.BigchainDbApi; 9 | import com.bigchaindb.model.BigChainDBGlobals; 10 | import com.bigchaindb.model.MetaDatas; 11 | import com.bigchaindb.util.JsonUtils; 12 | import com.bigchaindb.util.NetworkUtils; 13 | 14 | import okhttp3.Response; 15 | import org.slf4j.LoggerFactory; 16 | 17 | import java.io.IOException; 18 | 19 | /** 20 | * The Class MetaDataApi. 21 | */ 22 | public class MetaDataApi { 23 | 24 | private static final org.slf4j.Logger log = LoggerFactory.getLogger( MetaDataApi.class ); 25 | /** 26 | * Gets the metadata. 27 | * 28 | * @param searchKey the search key 29 | * @return the metadata 30 | * @throws IOException Signals that an I/O exception has occurred. 31 | */ 32 | public static MetaDatas getMetaData(String searchKey) throws IOException { 33 | log.debug( "getMetaData Call :" + searchKey ); 34 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.METADATA + "/?search="+ searchKey); 35 | String body = response.body().string(); 36 | response.close(); 37 | return JsonUtils.fromJson(body, MetaDatas.class); 38 | } 39 | 40 | /** 41 | * Gets the metadata with limit. 42 | * 43 | * @param searchKey the search key 44 | * @param limit the limit 45 | * @return the metadata with limit 46 | * @throws IOException Signals that an I/O exception has occurred. 47 | */ 48 | public static MetaDatas getMetaDataWithLimit(String searchKey, String limit) throws IOException { 49 | log.debug( "getMetaDataWithLimit Call :" + searchKey + " limit " + limit ); 50 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.METADATA + "/?search="+ searchKey+ "&limit=" + limit); 51 | String body = response.body().string(); 52 | response.close(); 53 | return JsonUtils.fromJson(body, MetaDatas.class); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/api/OutputsApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import com.bigchaindb.constants.BigchainDbApi; 9 | import com.bigchaindb.model.BigChainDBGlobals; 10 | import com.bigchaindb.model.Outputs; 11 | import com.bigchaindb.util.JsonUtils; 12 | import com.bigchaindb.util.NetworkUtils; 13 | 14 | import okhttp3.Response; 15 | import org.slf4j.LoggerFactory; 16 | 17 | import java.io.IOException; 18 | 19 | /** 20 | * The Class OutputsApi. 21 | */ 22 | public class OutputsApi { 23 | 24 | private static final org.slf4j.Logger log = LoggerFactory.getLogger( OutputsApi.class ); 25 | /** 26 | * Gets the outputs. 27 | * 28 | * @param publicKey the public key 29 | * @return the outputs 30 | * @throws IOException Signals that an I/O exception has occurred. 31 | */ 32 | public static Outputs getOutputs(String publicKey) throws IOException { 33 | log.debug( "getOutputs Call :" + publicKey ); 34 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.OUTPUTS + "?public_key="+ publicKey); 35 | String body = response.body().string(); 36 | response.close(); 37 | return JsonUtils.fromJson(body, Outputs.class); 38 | } 39 | 40 | /** 41 | * Gets the spent outputs. 42 | * 43 | * @param publicKey the public key 44 | * @return the spent outputs 45 | * @throws IOException Signals that an I/O exception has occurred. 46 | */ 47 | public static Outputs getSpentOutputs(String publicKey) throws IOException { 48 | log.debug( "getSpentOutputs Call :" + publicKey ); 49 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.OUTPUTS + "?public_key="+ publicKey+ "&spent=true"); 50 | String body = response.body().string(); 51 | response.close(); 52 | return JsonUtils.fromJson(body, Outputs.class); 53 | } 54 | 55 | /** 56 | * Gets the unspent outputs. 57 | * 58 | * @param publicKey the public key 59 | * @return the unspent outputs 60 | * @throws IOException Signals that an I/O exception has occurred. 61 | */ 62 | public static Outputs getUnspentOutputs(String publicKey) throws IOException { 63 | log.debug( "getUnspentOutputs Call :" + publicKey ); 64 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.OUTPUTS + "?public_key="+ publicKey+ "&spent=false"); 65 | String body = response.body().string(); 66 | response.close(); 67 | return JsonUtils.fromJson(body, Outputs.class); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/api/TransactionsApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import com.bigchaindb.constants.BigchainDbApi; 9 | import com.bigchaindb.constants.Operations; 10 | import com.bigchaindb.exceptions.TransactionNotFoundException; 11 | import com.bigchaindb.model.BigChainDBGlobals; 12 | import com.bigchaindb.model.GenericCallback; 13 | import com.bigchaindb.model.Transaction; 14 | import com.bigchaindb.model.Transactions; 15 | import com.bigchaindb.util.JsonUtils; 16 | import com.bigchaindb.util.NetworkUtils; 17 | 18 | import okhttp3.RequestBody; 19 | import okhttp3.Response; 20 | import org.apache.http.HttpStatus; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | import java.io.IOException; 25 | 26 | /** 27 | * The Class TransactionsApi. 28 | */ 29 | public class TransactionsApi extends AbstractApi { 30 | 31 | private static final Logger log = LoggerFactory.getLogger( TransactionsApi.class ); 32 | 33 | /** 34 | * Send transaction. 35 | * 36 | * @param transaction 37 | * the transaction 38 | * @param callback 39 | * the callback 40 | */ 41 | public static void sendTransaction(Transaction transaction, final GenericCallback callback) { 42 | log.debug( "sendTransaction Call :" + transaction ); 43 | RequestBody body = RequestBody.create(JSON, transaction.toString()); 44 | NetworkUtils.sendPostRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.TRANSACTIONS, body, callback); 45 | } 46 | 47 | /** 48 | * Sends the transaction. 49 | * 50 | * @param transaction 51 | * the transaction 52 | * @throws IOException 53 | * Signals that an I/O exception has occurred. 54 | */ 55 | public static void sendTransaction(Transaction transaction) throws IOException { 56 | log.debug( "sendTransaction Call :" + transaction ); 57 | RequestBody body = RequestBody.create(JSON, JsonUtils.toJson(transaction)); 58 | Response response = NetworkUtils.sendPostRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.TRANSACTIONS, body); 59 | response.close(); 60 | } 61 | 62 | /** 63 | * Gets the transaction by id. 64 | * 65 | * @param id 66 | * the id 67 | * @return the transaction by id 68 | * @throws IOException 69 | * Signals that an I/O exception has occurred. 70 | */ 71 | public static Transaction getTransactionById(String id) 72 | throws IOException, TransactionNotFoundException { 73 | log.debug( "getTransactionById Call :" + id ); 74 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.TRANSACTIONS + "/" + id); 75 | if(!response.isSuccessful()){ 76 | if(response.code() == HttpStatus.SC_NOT_FOUND) 77 | throw new TransactionNotFoundException("Transaction with id " + id + " not present"); 78 | } 79 | String body = response.body().string(); 80 | response.close(); 81 | return JsonUtils.fromJson(body, Transaction.class); 82 | } 83 | 84 | /** 85 | * Gets the transactions by asset id. 86 | * 87 | * @param assetId 88 | * the asset id 89 | * @param operation 90 | * the operation 91 | * @return the transactions by asset id 92 | * @throws IOException 93 | * Signals that an I/O exception has occurred. 94 | */ 95 | public static Transactions getTransactionsByAssetId(String assetId, Operations operation) 96 | throws IOException { 97 | log.debug( "getTransactionsByAssetId Call :" + assetId + " operation " + operation ); 98 | Response response = NetworkUtils.sendGetRequest( 99 | BigChainDBGlobals.getBaseUrl() + BigchainDbApi.TRANSACTIONS + "?asset_id=" + assetId + "&operation=" + operation); 100 | String body = response.body().string(); 101 | response.close(); 102 | return JsonUtils.fromJson(body, Transactions.class); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/api/ValidatorsApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import com.bigchaindb.constants.BigchainDbApi; 9 | import com.bigchaindb.model.BigChainDBGlobals; 10 | import com.bigchaindb.model.Validators; 11 | import com.bigchaindb.util.JsonUtils; 12 | import com.bigchaindb.util.NetworkUtils; 13 | 14 | import okhttp3.Response; 15 | import org.slf4j.LoggerFactory; 16 | 17 | import java.io.IOException; 18 | 19 | /** 20 | * The Class ValidatorsApi. 21 | */ 22 | public class ValidatorsApi { 23 | 24 | private static final org.slf4j.Logger log = LoggerFactory.getLogger( ValidatorsApi.class ); 25 | 26 | /** 27 | * Gets the the local validators set of a given node. 28 | * 29 | * @return the validators 30 | * @throws IOException Signals that an I/O exception has occurred. 31 | */ 32 | public static Validators getValidators() throws IOException { 33 | log.debug( "getValidators Call" ); 34 | Response response = NetworkUtils.sendGetRequest(BigChainDBGlobals.getBaseUrl() + BigchainDbApi.VALIDATORS); 35 | String body = response.body().string(); 36 | response.close(); 37 | return JsonUtils.fromJson(body, Validators.class); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/constants/BigchainDbApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.constants; 7 | 8 | 9 | 10 | /** 11 | * The Enum BigchainDbApi. 12 | */ 13 | public enum BigchainDbApi { 14 | 15 | /** The api version. */ 16 | // version. 17 | API_VERSION("/v1"), 18 | 19 | /** The streams. */ 20 | // Websocket 21 | STREAMS("/streams/valid_transactions"), 22 | 23 | /** The assets. */ 24 | // Core models 25 | ASSETS("/assets"), 26 | 27 | /** The metadata. */ 28 | METADATA("/metadata"), 29 | 30 | /** The outputs. */ 31 | OUTPUTS("/outputs"), 32 | 33 | /** The blocks. */ 34 | BLOCKS("/blocks"), 35 | 36 | /** The validators. */ 37 | VALIDATORS("/validators"), 38 | 39 | /** The transactions. */ 40 | TRANSACTIONS("/transactions"); 41 | 42 | /** The value. */ 43 | private final String value; 44 | 45 | 46 | /** 47 | * Instantiates a new bigchain db api. 48 | * 49 | * @param value the value 50 | */ 51 | BigchainDbApi(final String value) { 52 | this.value = value; 53 | } 54 | 55 | /* (non-Javadoc) 56 | * @see java.lang.Enum#toString() 57 | */ 58 | @Override 59 | public String toString() { 60 | return this.value; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/constants/Operations.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.constants; 7 | 8 | 9 | 10 | /** 11 | * The Enum Operations. 12 | */ 13 | public enum Operations { 14 | 15 | /** The create. */ 16 | CREATE("CREATE"), 17 | 18 | /** The transfer. */ 19 | TRANSFER("TRANSFER"); 20 | 21 | /** The value. */ 22 | private final String value; 23 | 24 | /** 25 | * Instantiates a new operations. 26 | * 27 | * @param value the value 28 | */ 29 | Operations(final String value) { 30 | this.value = value; 31 | } 32 | 33 | /* (non-Javadoc) 34 | * @see java.lang.Enum#toString() 35 | */ 36 | @Override 37 | public String toString() { 38 | return this.value; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/exceptions/TransactionNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.bigchaindb.exceptions; 2 | 3 | public class TransactionNotFoundException extends Exception { 4 | 5 | public TransactionNotFoundException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/factory/GsonEmptyCheckTypeAdapterFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.factory; 7 | 8 | import com.google.gson.Gson; 9 | import com.google.gson.TypeAdapterFactory; 10 | import com.google.gson.TypeAdapter; 11 | import com.google.gson.reflect.TypeToken; 12 | import com.google.gson.JsonElement; 13 | import com.google.gson.JsonObject; 14 | import com.google.gson.stream.JsonReader; 15 | import com.google.gson.stream.JsonWriter; 16 | 17 | import java.io.IOException; 18 | import java.util.Map; 19 | 20 | /** 21 | * Change empty Maps to null 22 | * Source http://chrisjenx.com/gson-empty-json-to-null/ 23 | */ 24 | public class GsonEmptyCheckTypeAdapterFactory implements TypeAdapterFactory { 25 | 26 | @Override 27 | public TypeAdapter create(final Gson gson, final TypeToken type) { 28 | // We filter out the EmptyCheckTypeAdapter as we need to check this for emptiness! 29 | if (Map.class.isAssignableFrom(type.getRawType())) { 30 | final TypeAdapter delegate = gson.getDelegateAdapter(this, type); 31 | final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); 32 | return new EmptyCheckTypeAdapter<>(delegate, elementAdapter).nullSafe(); 33 | } 34 | return null; 35 | } 36 | 37 | static public class EmptyCheckTypeAdapter extends TypeAdapter { 38 | private final TypeAdapter delegate; 39 | private final TypeAdapter elementAdapter; 40 | 41 | public EmptyCheckTypeAdapter(final TypeAdapter delegate, final TypeAdapter elementAdapter) { 42 | this.delegate = delegate; 43 | this.elementAdapter = elementAdapter; 44 | } 45 | 46 | @Override 47 | public void write(final JsonWriter out, final T value) throws IOException { 48 | this.delegate.write(out, value); 49 | } 50 | 51 | @Override 52 | public T read(final JsonReader in) throws IOException { 53 | final JsonObject asJsonObject = elementAdapter.read(in).getAsJsonObject(); 54 | if (asJsonObject.entrySet().isEmpty()) return null; 55 | return this.delegate.fromJsonTree(asJsonObject); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/AssetSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.model.Asset; 9 | import com.bigchaindb.util.JsonUtils; 10 | import com.google.gson.*; 11 | 12 | import java.lang.reflect.Type; 13 | 14 | public class AssetSerializer implements JsonSerializer 15 | { 16 | /** 17 | * Serialize an asset object to json object 18 | * Note: given the type of the asset.data it maybe necessary to 19 | * to add a type adapter {@link JsonSerializer} and/or {@link JsonDeserializer} with {@link JsonUtils} and 20 | * {@link com.bigchaindb.util.JsonUtils#addTypeAdapterSerializer} 21 | * 22 | * TODO test user.data with custom serializer 23 | * 24 | * @param src object to serialize 25 | * @param typeOfSrc type of src 26 | * @param context the json context 27 | * @return the json object 28 | */ 29 | public JsonElement serialize( Asset src, Type typeOfSrc, JsonSerializationContext context ) 30 | { 31 | Gson gson = JsonUtils.getGson(); 32 | JsonObject asset = new JsonObject(); 33 | 34 | if (src.getData() != null) { 35 | asset.add( "data", gson.toJsonTree( src.getData(), src.getDataClass() ) ); 36 | } else { 37 | asset.add("id", gson.toJsonTree( src.getId() )); 38 | } 39 | 40 | return asset; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/AssetsDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.model.Asset; 9 | import com.bigchaindb.model.Assets; 10 | import com.bigchaindb.util.JsonUtils; 11 | import com.google.gson.JsonDeserializationContext; 12 | import com.google.gson.JsonDeserializer; 13 | import com.google.gson.JsonElement; 14 | import com.google.gson.JsonParseException; 15 | 16 | import java.lang.reflect.Type; 17 | 18 | /** 19 | * The Class AssetsDeserializer. 20 | */ 21 | public class AssetsDeserializer implements JsonDeserializer { 22 | 23 | /* (non-Javadoc) 24 | * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) 25 | */ 26 | @Override 27 | public Assets deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 28 | throws JsonParseException { 29 | 30 | Assets assets = new Assets(); 31 | for( JsonElement jElement: json.getAsJsonArray() ) { 32 | assets.addAsset(JsonUtils.fromJson(jElement.getAsJsonObject().toString(), Asset.class)); 33 | } 34 | return assets; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/CustomExclusionStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.annotations.Exclude; 9 | import com.google.gson.ExclusionStrategy; 10 | import com.google.gson.FieldAttributes; 11 | 12 | 13 | 14 | /** 15 | * The Class CustomExclusionStrategy. 16 | */ 17 | public class CustomExclusionStrategy implements ExclusionStrategy { 18 | 19 | /* (non-Javadoc) 20 | * @see com.google.gson.ExclusionStrategy#shouldSkipField(com.google.gson.FieldAttributes) 21 | */ 22 | public boolean shouldSkipField(FieldAttributes f) { 23 | if(f.getAnnotation(Exclude.class)!=null){ 24 | return true; 25 | } 26 | return false; 27 | } 28 | 29 | /* (non-Javadoc) 30 | * @see com.google.gson.ExclusionStrategy#shouldSkipClass(java.lang.Class) 31 | */ 32 | public boolean shouldSkipClass(Class clazz) { 33 | return false; 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/InputSerializer.java: -------------------------------------------------------------------------------- 1 | package com.bigchaindb.json.strategy; 2 | 3 | import com.bigchaindb.model.Input; 4 | import com.bigchaindb.util.JsonUtils; 5 | import com.google.gson.*; 6 | 7 | import java.lang.reflect.Type; 8 | 9 | 10 | /** 11 | * Serialize an input record. 12 | */ 13 | public class InputSerializer implements JsonSerializer 14 | { 15 | /** 16 | * Serialize an input object. 17 | * 18 | * @param src object to serialize 19 | * @param typeOfSrc type of src 20 | * @param context the json context 21 | * @return the json object 22 | */ 23 | public JsonElement serialize(Input src, Type typeOfSrc, JsonSerializationContext context ) 24 | { 25 | Gson gson = JsonUtils.getGson(); 26 | JsonObject asset = new JsonObject(); 27 | 28 | 29 | if (src.getFullFillment() != null) { 30 | asset.add( "fulfillment", gson.toJsonTree( src.getFullFillment() ) ); 31 | } else { 32 | asset.add( "fulfillment", gson.toJsonTree( src.getFullFillmentDetails() ) ); 33 | } 34 | asset.add( "fulfills", gson.toJsonTree( src.getFulFills() ) ); 35 | asset.add( "owners_before", gson.toJsonTree( src.getOwnersBefore() ) ); 36 | 37 | return asset; 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/MetaDataDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.model.MetaData; 9 | import com.bigchaindb.model.MetaDatas; 10 | import com.bigchaindb.util.JsonUtils; 11 | import com.google.gson.JsonDeserializationContext; 12 | import com.google.gson.JsonDeserializer; 13 | import com.google.gson.JsonElement; 14 | import com.google.gson.JsonParseException; 15 | 16 | import java.lang.reflect.Type; 17 | 18 | /** 19 | * The Class AssetsDeserializer. 20 | */ 21 | public class MetaDataDeserializer implements JsonDeserializer { 22 | 23 | /* (non-Javadoc) 24 | * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) 25 | */ 26 | @Override 27 | public MetaDatas deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 28 | throws JsonParseException { 29 | 30 | MetaDatas metaDatas = new MetaDatas(); 31 | for( JsonElement jElement: json.getAsJsonArray() ) { 32 | metaDatas.addMetaData(JsonUtils.fromJson(jElement.getAsJsonObject().toString(), MetaData.class)); 33 | } 34 | return metaDatas; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/MetaDataSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.model.MetaData; 9 | import com.bigchaindb.util.JsonUtils; 10 | import com.google.gson.*; 11 | import com.google.gson.reflect.TypeToken; 12 | 13 | import java.lang.reflect.Type; 14 | import java.util.Map; 15 | 16 | public class MetaDataSerializer implements JsonSerializer 17 | { 18 | /** 19 | * 20 | * @param src object to serialize 21 | * @param typeOfSrc type of src 22 | * @param context the json context 23 | * @return the json object 24 | */ 25 | public JsonElement serialize( MetaData src, Type typeOfSrc, JsonSerializationContext context ) 26 | { 27 | Gson gson = JsonUtils.getGson(); 28 | JsonElement metadata = gson.toJsonTree( src.getMetadata(), new TypeToken>() { }.getType() ); 29 | return metadata; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/OutputsDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.model.Output; 9 | import com.bigchaindb.model.Outputs; 10 | import com.google.gson.JsonDeserializationContext; 11 | import com.google.gson.JsonDeserializer; 12 | import com.google.gson.JsonElement; 13 | import com.google.gson.JsonParseException; 14 | 15 | import java.lang.reflect.Type; 16 | import java.util.Iterator; 17 | 18 | 19 | 20 | /** 21 | * The Class OutputsDeserializer. 22 | */ 23 | public class OutputsDeserializer implements JsonDeserializer { 24 | 25 | /* (non-Javadoc) 26 | * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) 27 | */ 28 | @Override 29 | public Outputs deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 30 | throws JsonParseException { 31 | 32 | Outputs outputs = new Outputs(); 33 | Iterator jsonIter = json.getAsJsonArray().iterator(); 34 | while(jsonIter.hasNext()) { 35 | Output output = new Output(); 36 | JsonElement jElement = jsonIter.next(); 37 | output.setTransactionId(jElement.getAsJsonObject().get("transaction_id").toString().replace("\"", "")); 38 | output.setOutputIndex(Integer.parseInt(jElement.getAsJsonObject().get("output_index").toString().replace("\"", ""))); 39 | outputs.addOutput(output); 40 | } 41 | return outputs; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/TransactionDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.model.Asset; 9 | import com.bigchaindb.model.Input; 10 | import com.bigchaindb.model.Output; 11 | import com.bigchaindb.model.Transaction; 12 | import com.bigchaindb.util.JsonUtils; 13 | import com.google.gson.JsonDeserializationContext; 14 | import com.google.gson.JsonDeserializer; 15 | import com.google.gson.JsonElement; 16 | import com.google.gson.JsonParseException; 17 | import java.lang.reflect.Type; 18 | import java.util.Map; 19 | 20 | /** 21 | * The Class TransactionsDeserializer. 22 | */ 23 | public class TransactionDeserializer implements JsonDeserializer { 24 | private static Class metaDataClass = Map.class; 25 | 26 | /** 27 | * Set a custom metadata class the class that is serialized should be symmetrical with the class that is deserialized. 28 | * 29 | * @param metaDataType the metaData class 30 | */ 31 | public static void setMetaDataClass( Class metaDataType ) 32 | { 33 | metaDataClass = metaDataType; 34 | } 35 | 36 | /* 37 | * (non-Javadoc) 38 | * 39 | * @see 40 | * com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, 41 | * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) 42 | */ 43 | @SuppressWarnings("unchecked") 44 | @Override 45 | public Transaction deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException 46 | { 47 | Transaction transaction = new Transaction(); 48 | JsonElement jElement = json.getAsJsonObject(); 49 | 50 | transaction.setAsset( JsonUtils.fromJson(jElement.getAsJsonObject().get("asset").toString(), Asset.class)); 51 | transaction.setMetaData( JsonUtils.fromJson( jElement.getAsJsonObject().get("metadata").toString(), metaDataClass )); 52 | transaction.setId(jElement.getAsJsonObject().get("id").toString().replace("\"", "")); 53 | 54 | for( JsonElement jInputElement: jElement.getAsJsonObject().get("inputs").getAsJsonArray() ) { 55 | transaction.addInput(JsonUtils.fromJson(jInputElement.toString(), Input.class)); 56 | } 57 | 58 | for( JsonElement jOutputElement: jElement.getAsJsonObject().get("outputs").getAsJsonArray() ) { 59 | transaction.addOutput(JsonUtils.fromJson(jOutputElement.toString(), Output.class)); 60 | } 61 | 62 | transaction.setOperation(jElement.getAsJsonObject().get("operation").toString()); 63 | transaction.setVersion(jElement.getAsJsonObject().get("version").toString()); 64 | 65 | return transaction; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/TransactionIdExclusionStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.google.gson.ExclusionStrategy; 9 | import com.google.gson.FieldAttributes; 10 | 11 | public class TransactionIdExclusionStrategy implements ExclusionStrategy 12 | { 13 | public boolean shouldSkipClass( Class klass ) 14 | { 15 | return false; 16 | } 17 | 18 | public boolean shouldSkipField( FieldAttributes f ) 19 | { 20 | //return f.getDeclaringClass() == Transaction.class && f.getName().equals( "id" ); 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/TransactionsDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.model.*; 9 | import com.bigchaindb.util.JsonUtils; 10 | import com.google.gson.JsonDeserializationContext; 11 | import com.google.gson.JsonDeserializer; 12 | import com.google.gson.JsonElement; 13 | import com.google.gson.JsonParseException; 14 | 15 | import java.lang.reflect.Type; 16 | import java.util.Map; 17 | 18 | /** 19 | * The Class TransactionsDeserializer. 20 | */ 21 | public class TransactionsDeserializer implements JsonDeserializer { 22 | private static Class metaDataClass = Map.class; 23 | 24 | public static void setMetaDataClass( Class metaDataType ) 25 | { 26 | metaDataClass = metaDataType; 27 | } 28 | 29 | /* (non-Javadoc) 30 | * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) 31 | */ 32 | @SuppressWarnings("unchecked") 33 | @Override 34 | public Transactions deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 35 | throws JsonParseException { 36 | 37 | Transactions transactions = new Transactions(); 38 | 39 | for( JsonElement jElement: json.getAsJsonArray() ) { 40 | Transaction transaction = new Transaction(); 41 | 42 | transaction.setAsset(JsonUtils.fromJson(jElement.getAsJsonObject().get("asset").toString(), Asset.class)); 43 | transaction.setMetaData( JsonUtils.fromJson( jElement.getAsJsonObject().get("metadata").toString(), metaDataClass )); 44 | transaction.setId(jElement.getAsJsonObject().get("id").toString()); 45 | 46 | for( JsonElement jInputElement: jElement.getAsJsonObject().get("inputs").getAsJsonArray() ) { 47 | transaction.addInput(JsonUtils.fromJson(jInputElement.toString(), Input.class)); 48 | } 49 | 50 | for( JsonElement jOutputElement: jElement.getAsJsonObject().get("outputs").getAsJsonArray() ) { 51 | transaction.addOutput(JsonUtils.fromJson(jOutputElement.toString(), Output.class)); 52 | } 53 | 54 | transaction.setOperation(jElement.getAsJsonObject().get("operation").toString()); 55 | transaction.setVersion(jElement.getAsJsonObject().get("version").toString()); 56 | 57 | transactions.addTransaction(transaction); 58 | 59 | } 60 | return transactions; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/json/strategy/ValidatorDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.json.strategy; 7 | 8 | import com.bigchaindb.model.Validator; 9 | import com.bigchaindb.model.Validators; 10 | import com.bigchaindb.util.JsonUtils; 11 | import com.google.gson.JsonDeserializationContext; 12 | import com.google.gson.JsonDeserializer; 13 | import com.google.gson.JsonElement; 14 | import com.google.gson.JsonParseException; 15 | 16 | import java.lang.reflect.Type; 17 | import java.util.Iterator; 18 | 19 | 20 | 21 | /** 22 | * The Class ValidatorDeserializer. 23 | */ 24 | public class ValidatorDeserializer implements JsonDeserializer { 25 | 26 | /* (non-Javadoc) 27 | * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) 28 | */ 29 | @Override 30 | public Validators deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 31 | throws JsonParseException { 32 | 33 | Validators validators = new Validators(); 34 | Iterator jsonIter = json.getAsJsonArray().iterator(); 35 | while(jsonIter.hasNext()) { 36 | JsonElement jElement = jsonIter.next(); 37 | validators.addValidator(JsonUtils.fromJson(jElement.getAsJsonObject().toString(), Validator.class)); 38 | } 39 | return validators; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Account.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import java.security.PrivateKey; 9 | import java.security.PublicKey; 10 | import java.security.spec.InvalidKeySpecException; 11 | import java.security.spec.PKCS8EncodedKeySpec; 12 | import java.security.spec.X509EncodedKeySpec; 13 | 14 | import net.i2p.crypto.eddsa.EdDSAPrivateKey; 15 | import net.i2p.crypto.eddsa.EdDSAPublicKey; 16 | import net.i2p.crypto.eddsa.Utils; 17 | 18 | 19 | /** 20 | * The Class Account. 21 | */ 22 | public class Account { 23 | 24 | /** The public key. */ 25 | private PublicKey publicKey; 26 | 27 | /** The private key. */ 28 | private PrivateKey privateKey; 29 | 30 | /** 31 | * Gets the public key. 32 | * 33 | * @return the public key 34 | */ 35 | public PublicKey getPublicKey() { 36 | return publicKey; 37 | } 38 | 39 | /** 40 | * Sets the public key. 41 | * 42 | * @param publicKey the new public key 43 | */ 44 | public void setPublicKey(PublicKey publicKey) { 45 | this.publicKey = publicKey; 46 | } 47 | 48 | /** 49 | * Gets the private key. 50 | * 51 | * @return the private key 52 | */ 53 | public PrivateKey getPrivateKey() { 54 | return privateKey; 55 | } 56 | 57 | /** 58 | * Sets the private key. 59 | * 60 | * @param privateKey the new private key 61 | */ 62 | public void setPrivateKey(PrivateKey privateKey) { 63 | this.privateKey = privateKey; 64 | } 65 | 66 | /** 67 | * Private key from hex. 68 | * 69 | * @param hex the hex 70 | * @return the private key 71 | * @throws InvalidKeySpecException the invalid key spec exception 72 | */ 73 | public static PrivateKey privateKeyFromHex(String hex) throws InvalidKeySpecException { 74 | 75 | final PKCS8EncodedKeySpec encoded = new PKCS8EncodedKeySpec(Utils.hexToBytes(hex)); 76 | final PrivateKey privKey = new EdDSAPrivateKey(encoded); 77 | 78 | return privKey; 79 | 80 | } 81 | 82 | /** 83 | * Public key from hex. 84 | * 85 | * @param hex the hex 86 | * @return the public key 87 | * @throws InvalidKeySpecException the invalid key spec exception 88 | */ 89 | public static PublicKey publicKeyFromHex(String hex) throws InvalidKeySpecException { 90 | final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Utils.hexToBytes(hex)); 91 | final PublicKey pubKey = new EdDSAPublicKey(pubKeySpec); 92 | 93 | return pubKey; 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/ApiEndpoints.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | /** 9 | * The Class ApiEndpoints. 10 | */ 11 | public class ApiEndpoints { 12 | 13 | /** The assets. */ 14 | private String assets; 15 | 16 | /** The docs. */ 17 | private String docs; 18 | 19 | /** The outputs. */ 20 | private String outputs; 21 | 22 | /** The validators. */ 23 | private String validators; 24 | 25 | /** The streams. */ 26 | private String streams; 27 | 28 | /** The transactions. */ 29 | private String transactions; 30 | 31 | /** The metadata. */ 32 | private String metadata; 33 | 34 | /** 35 | * Gets the assets. 36 | * 37 | * @return the assets 38 | */ 39 | public String getAssets() { 40 | return assets; 41 | } 42 | 43 | /** 44 | * Gets the docs. 45 | * 46 | * @return the docs 47 | */ 48 | public String getDocs() { 49 | return docs; 50 | } 51 | 52 | /** 53 | * Gets the outputs. 54 | * 55 | * @return the outputs 56 | */ 57 | public String getOutputs() { 58 | return outputs; 59 | } 60 | 61 | /** 62 | * Gets the validators. 63 | * 64 | * @return the validators 65 | */ 66 | public String getValidators() { 67 | return validators; 68 | } 69 | 70 | /** 71 | * Gets the streams. 72 | * 73 | * @return the streams 74 | */ 75 | public String getStreams() { 76 | return streams; 77 | } 78 | 79 | /** 80 | * Gets the transactions. 81 | * 82 | * @return the transactions 83 | */ 84 | public String getTransactions() { 85 | return transactions; 86 | } 87 | 88 | /** 89 | * Gets the metadata. 90 | * 91 | * @return the metadata 92 | */ 93 | public String getMetadata() { 94 | return metadata; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Asset.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.bigchaindb.annotations.Exclude; 9 | import com.google.gson.annotations.SerializedName; 10 | 11 | import java.io.Serializable; 12 | 13 | /* 14 | * The Class Asset. 15 | */ 16 | public class Asset implements Serializable { 17 | 18 | /** 19 | * 20 | */ 21 | private static final long serialVersionUID = 163400160721472722L; 22 | 23 | /** The id. */ 24 | @SerializedName("id") 25 | @Exclude 26 | private String id; 27 | 28 | /** The data. */ 29 | @SerializedName("data") 30 | private Object data; 31 | 32 | /** the data class the type of the data class needed for serialization/deserialization */ 33 | @Exclude 34 | private Class dataClass = com.google.gson.internal.LinkedTreeMap.class; 35 | 36 | /** 37 | * Instantiates a new asset. 38 | */ 39 | public Asset() {} 40 | 41 | /** 42 | * Instantiates a new asset. 43 | * 44 | * @param data the data 45 | * @param dataClass due to type erasure the data class needs to be provided for serialization/deserialization 46 | */ 47 | public Asset(Object data, Class dataClass) { 48 | this.data = data; 49 | this.dataClass = dataClass; 50 | } 51 | 52 | /** 53 | * Instantiates a new asset by reference. 54 | * 55 | * @param id ID of the asset. 56 | */ 57 | public Asset(String id) { 58 | this.id = id; 59 | } 60 | 61 | /** 62 | * Gets the data. 63 | * 64 | * @return the data 65 | */ 66 | public Object getData() { 67 | return data; 68 | } 69 | 70 | /** 71 | * return the type of the Asset data class 72 | * 73 | * @return the data class type 74 | */ 75 | public Class getDataClass() 76 | { 77 | return dataClass; 78 | } 79 | 80 | /** 81 | * Gets the id. 82 | * 83 | * @return the id 84 | */ 85 | public String getId() { 86 | return id; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Assets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | 12 | 13 | /** 14 | * The Class Assets. 15 | */ 16 | public class Assets { 17 | 18 | /** The assets. */ 19 | private List assets = new ArrayList(); 20 | 21 | /** 22 | * Gets the assets. 23 | * 24 | * @return the assets 25 | */ 26 | public List getAssets() { 27 | return assets; 28 | } 29 | 30 | /** 31 | * Adds the asset. 32 | * 33 | * @param asset the asset 34 | */ 35 | public void addAsset(Asset asset) { 36 | this.assets.add(asset); 37 | } 38 | 39 | /** 40 | * How many assets are there 41 | * 42 | * @return the number of assets 43 | */ 44 | public int size() 45 | { 46 | return assets != null ? assets.size() : 0; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/BigChainDBGlobals.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | import okhttp3.OkHttpClient; 12 | 13 | 14 | /** 15 | * The Class Globals. 16 | */ 17 | public class BigChainDBGlobals { 18 | 19 | /** The api endpoints. */ 20 | private static ApiEndpoints apiEndpoints; 21 | 22 | /** 23 | * Gets the api endpoints. 24 | * 25 | * @return the api endpoints 26 | */ 27 | public static ApiEndpoints getApiEndpoints() { 28 | return apiEndpoints; 29 | } 30 | 31 | /** 32 | * Sets the api endpoints. 33 | * 34 | * @param apiEndpoints the new api endpoints 35 | */ 36 | public static void setApiEndpoints(ApiEndpoints apiEndpoints) { 37 | BigChainDBGlobals.apiEndpoints = apiEndpoints; 38 | } 39 | 40 | /** The authorization tokens. */ 41 | private static Map authorizationTokens; 42 | 43 | /** The base url. */ 44 | private static String baseUrl; 45 | 46 | /** The http client. */ 47 | private static OkHttpClient httpClient; 48 | 49 | /** The ws socket url. */ 50 | private static String wsSocketUrl; 51 | 52 | /** 53 | * Gets the ws socket url. 54 | * 55 | * @return the ws socket url 56 | */ 57 | public static String getWsSocketUrl() { 58 | return wsSocketUrl; 59 | } 60 | 61 | /** 62 | * Sets the ws socket url. 63 | * 64 | * @param wsSocketUrl the new ws socket url 65 | */ 66 | public static void setWsSocketUrl(String wsSocketUrl) { 67 | BigChainDBGlobals.wsSocketUrl = wsSocketUrl; 68 | } 69 | 70 | /** 71 | * Gets the authorization tokens. 72 | * 73 | * @return the authorization tokens 74 | */ 75 | public static Map getAuthorizationTokens() { 76 | return authorizationTokens; 77 | } 78 | 79 | /** 80 | * Sets the authorization tokens. 81 | * 82 | * @param authorizationTokens the authorization tokens 83 | */ 84 | public static void setAuthorizationTokens(Map authorizationTokens) { 85 | BigChainDBGlobals.authorizationTokens = authorizationTokens; 86 | } 87 | 88 | /** 89 | * Gets the base url. 90 | * 91 | * @return the base url 92 | */ 93 | public static String getBaseUrl() { 94 | return baseUrl; 95 | } 96 | 97 | /** 98 | * Sets the base url. 99 | * 100 | * @param baseUrl the new base url 101 | */ 102 | public static void setBaseUrl(String baseUrl) { 103 | BigChainDBGlobals.baseUrl = baseUrl; 104 | } 105 | 106 | /** 107 | * Gets the http client. 108 | * 109 | * @return the http client 110 | */ 111 | public static OkHttpClient getHttpClient() { 112 | return httpClient; 113 | } 114 | 115 | /** 116 | * Sets the http client. 117 | * 118 | * @param httpClient the new http client 119 | */ 120 | public static void setHttpClient(OkHttpClient httpClient) { 121 | BigChainDBGlobals.httpClient = httpClient; 122 | } 123 | 124 | /** 125 | * indicates if connection to a node still successful 126 | */ 127 | private static boolean isConnected; 128 | /** 129 | * timeout (defaults to 20000 ms) 130 | */ 131 | protected static int timeout = 20000; 132 | /** 133 | * time to wait till timeout is reached 134 | */ 135 | private static long timeTillTimeout = System.currentTimeMillis() + timeout; 136 | /** 137 | * list of nodes to connect to 138 | */ 139 | private static List connections; 140 | /** 141 | * delay added if connection failed 142 | */ 143 | public static final int DELAY = 500; 144 | /** 145 | * current connected node 146 | */ 147 | private static Connection currentNode; 148 | 149 | /** 150 | * check if there are multiple nodes used 151 | * @return boolean 152 | */ 153 | private static boolean hasMultipleNodes = false; 154 | 155 | 156 | public static boolean isHasMultipleNodes() { 157 | return hasMultipleNodes; 158 | } 159 | 160 | public static void setHasMultipleNodes(boolean hasMultipleNodes) { 161 | BigChainDBGlobals.hasMultipleNodes = hasMultipleNodes; 162 | } 163 | 164 | public static Connection getCurrentNode() { 165 | return currentNode; 166 | } 167 | 168 | public static void setCurrentNode(Connection currentNode) { 169 | BigChainDBGlobals.currentNode = currentNode; 170 | } 171 | 172 | public static long getTimeTillTimeout() { 173 | return timeTillTimeout; 174 | } 175 | 176 | public static long calculateTimeTillTimeout() { 177 | return timeTillTimeout - System.currentTimeMillis(); 178 | } 179 | 180 | public static void resetTimeTillTimeout() { 181 | BigChainDBGlobals.timeTillTimeout = System.currentTimeMillis() 182 | + BigChainDBGlobals.getTimeout(); 183 | } 184 | 185 | public static int getTimeout() { 186 | return timeout; 187 | } 188 | 189 | public static void setTimeout(int timeout) { 190 | BigChainDBGlobals.timeout = timeout; 191 | } 192 | 193 | public static boolean isConnected() { 194 | return isConnected; 195 | } 196 | 197 | public static void setConnected(boolean isConnected) { 198 | BigChainDBGlobals.isConnected = isConnected; 199 | } 200 | 201 | 202 | public static List getConnections() { 203 | return connections; 204 | } 205 | 206 | public static void setConnections(List connections) { 207 | BigChainDBGlobals.connections = connections; 208 | } 209 | 210 | } 211 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Block.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | import java.util.List; 11 | 12 | 13 | /** 14 | * The Class Block. 15 | */ 16 | public class Block { 17 | 18 | /** 19 | * The id. 20 | */ 21 | @SerializedName("height") 22 | private Integer height; 23 | 24 | /** 25 | * The transactions. 26 | */ 27 | @SerializedName("transactions") 28 | private List transactions; 29 | 30 | /** 31 | * Gets the height. 32 | * 33 | * @return the height 34 | */ 35 | public Integer getHeight() { 36 | return height; 37 | } 38 | 39 | /** 40 | * Gets the transactions. 41 | * 42 | * @return the transactions 43 | */ 44 | public List getTransactions() { 45 | return transactions; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Condition.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | import java.io.Serializable; 11 | 12 | 13 | 14 | /** 15 | * The Class Condition. 16 | */ 17 | public class Condition implements Serializable { 18 | 19 | /** The Constant serialVersionUID. */ 20 | private static final long serialVersionUID = 1L; 21 | 22 | /** The details. */ 23 | @SerializedName("details") 24 | private Details details; 25 | 26 | /** The uri. */ 27 | @SerializedName("uri") 28 | private String uri; 29 | 30 | /** 31 | * Instantiates a new condition. 32 | */ 33 | public Condition() { 34 | } 35 | 36 | /** 37 | * Instantiates a new condition. 38 | * 39 | * @param details the details 40 | * @param uri the uri 41 | */ 42 | public Condition(Details details, String uri) { 43 | this.details = details; 44 | this.uri = uri; 45 | } 46 | 47 | /** 48 | * Gets the details. 49 | * 50 | * @return the details 51 | */ 52 | public Details getDetails() { 53 | return details; 54 | } 55 | 56 | /** 57 | * Gets the uri. 58 | * 59 | * @return the uri 60 | */ 61 | public String getUri() { 62 | return uri; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Connection.java: -------------------------------------------------------------------------------- 1 | package com.bigchaindb.model; 2 | 3 | import java.util.Map; 4 | 5 | public class Connection { 6 | 7 | /** 8 | * node details 9 | */ 10 | private Map connection; 11 | /** 12 | * how many times this node tried to connect and failed? 13 | */ 14 | private int retryCount = 0; 15 | /** 16 | * when is the next time this node should try to connect? 17 | */ 18 | private long timeToRetryForConnection = 0; 19 | 20 | public Connection(Map connection) { 21 | this.connection = connection; 22 | } 23 | 24 | public Map getConnection() { 25 | return connection; 26 | } 27 | 28 | public int getRetryCount() { 29 | return retryCount; 30 | } 31 | 32 | public void setRetryCount(int retryCount) { 33 | this.retryCount = retryCount; 34 | } 35 | 36 | public long getTimeToRetryForConnection() { 37 | return timeToRetryForConnection; 38 | } 39 | 40 | public void setTimeToRetryForConnection(long timeToRetryForConnection) { 41 | this.timeToRetryForConnection = timeToRetryForConnection; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/DataModel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.bigchaindb.util.JsonUtils; 9 | import com.google.gson.reflect.TypeToken; 10 | import java.lang.reflect.Type; 11 | import java.util.Map; 12 | 13 | public abstract class DataModel { 14 | 15 | /** 16 | * To map string. 17 | * 18 | * @return the map 19 | */ 20 | public Map toMapString() { 21 | Type mapType = new TypeToken>(){}.getType(); 22 | Map son = JsonUtils.getGson().fromJson(JsonUtils.toJson(this), mapType); 23 | return son; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Details.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | import java.io.Serializable; 11 | 12 | 13 | 14 | /** 15 | * The Class Details. 16 | */ 17 | public class Details implements Serializable { 18 | 19 | /** The public key. */ 20 | @SerializedName("public_key") 21 | private String publicKey; 22 | 23 | /** The type. */ 24 | @SerializedName("type") 25 | private String type; 26 | 27 | /** 28 | * Gets the public key. 29 | * 30 | * @return the public key 31 | */ 32 | public String getPublicKey() { 33 | return publicKey; 34 | } 35 | 36 | /** 37 | * Sets the public key. 38 | * 39 | * @param publicKey the new public key 40 | */ 41 | public void setPublicKey(String publicKey) { 42 | this.publicKey = publicKey; 43 | } 44 | 45 | /** 46 | * Gets the type. 47 | * 48 | * @return the type 49 | */ 50 | public String getType() { 51 | return type; 52 | } 53 | 54 | /** 55 | * Sets the type. 56 | * 57 | * @param type the new type 58 | */ 59 | public void setType(String type) { 60 | this.type = type; 61 | } 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/FulFill.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | 11 | 12 | /** 13 | * The Class FulFill. 14 | */ 15 | public class FulFill { 16 | 17 | /** The output index. */ 18 | @SerializedName("output_index") 19 | private int outputIndex = 0; 20 | 21 | /** The transaction id. */ 22 | @SerializedName("transaction_id") 23 | private String transactionId = ""; 24 | 25 | /** 26 | * Gets the output index. 27 | * 28 | * @return the output index 29 | */ 30 | public Integer getOutputIndex() { 31 | return outputIndex; 32 | } 33 | 34 | /** 35 | * Sets the output index. 36 | * 37 | * @param outputIndex the new output index 38 | */ 39 | public void setOutputIndex(Integer outputIndex) { 40 | this.outputIndex = outputIndex; 41 | } 42 | 43 | /** 44 | * Gets the transaction id. 45 | * 46 | * @return the transaction id 47 | */ 48 | public String getTransactionId() { 49 | return transactionId; 50 | } 51 | 52 | /** 53 | * Sets the transaction id. 54 | * 55 | * @param transactionId the new transaction id 56 | */ 57 | public void setTransactionId(String transactionId) { 58 | this.transactionId = transactionId; 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/GenericCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import okhttp3.Response; 9 | 10 | 11 | 12 | /** 13 | * The Interface TransactionCallback. 14 | */ 15 | public interface GenericCallback { 16 | 17 | /** 18 | * The pushed transaction was accepted in the BACKLOG, but the processing has not been completed. 19 | * 20 | * @param response the response 21 | */ 22 | void pushedSuccessfully(Response response); 23 | 24 | /** 25 | * The transaction was malformed and not accepted in the BACKLOG. This shouldn't normally happen as the 26 | * driver ensures the proper transaction creation. 27 | * 28 | * @param response the response 29 | */ 30 | void transactionMalformed(Response response); 31 | 32 | /** 33 | * All other errors, including server malfunction or network error. 34 | * 35 | * @param response the response 36 | */ 37 | void otherError(Response response); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Input.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | import java.io.Serializable; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | 15 | 16 | /** 17 | * The Class Input. 18 | */ 19 | public class Input implements Serializable { 20 | 21 | /** The string fulillment, if applicable. */ 22 | @SerializedName("fulfillment") 23 | private String fullFillment = null; 24 | 25 | /** The fulfillment details, if applicable. */ 26 | private Details fullFillmentDetails = null; 27 | 28 | /** The ful fills. */ 29 | @SerializedName("fulfills") 30 | private FulFill fulFills = null; 31 | 32 | /** The owners before. */ 33 | @SerializedName("owners_before") 34 | private List ownersBefore = new ArrayList(); 35 | 36 | /** 37 | * Gets the full fillment. 38 | * 39 | * @return the full fillment 40 | */ 41 | public String getFullFillment() { 42 | return fullFillment; 43 | } 44 | 45 | /** 46 | * Gets the fulfillment details. 47 | * 48 | * @return fulfillment details. 49 | */ 50 | public Details getFullFillmentDetails() { 51 | return fullFillmentDetails; 52 | } 53 | 54 | /** 55 | * Sets the full fillment as a string. 56 | * 57 | * @param fullFillment the new full fillment 58 | */ 59 | public void setFullFillment(String fullFillment) { 60 | this.fullFillment = fullFillment; 61 | } 62 | 63 | /** 64 | * Sets the full fillment as a set of details. 65 | * 66 | * @param fullFillment the new full fillment 67 | */ 68 | public void setFullFillment(Details fullFillment) { 69 | this.fullFillmentDetails = fullFillment; 70 | } 71 | 72 | /** 73 | * Gets the ful fills. 74 | * 75 | * @return the ful fills 76 | */ 77 | public FulFill getFulFills() { 78 | return fulFills; 79 | } 80 | 81 | /** 82 | * Sets the ful fills. 83 | * 84 | * @param fulFills the new ful fills 85 | */ 86 | public void setFulFills(FulFill fulFills) { 87 | this.fulFills = fulFills; 88 | } 89 | 90 | /** 91 | * Gets the owners before. 92 | * 93 | * @return the owners before 94 | */ 95 | public List getOwnersBefore() { 96 | return ownersBefore; 97 | } 98 | 99 | /** 100 | * Adds the owner. 101 | * 102 | * @param owner the owner 103 | */ 104 | public void addOwner(String owner) { 105 | this.ownersBefore.add(owner); 106 | } 107 | 108 | 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/MetaData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | import java.util.Map; 11 | import java.util.TreeMap; 12 | 13 | 14 | 15 | /** 16 | * The Class MetaData. 17 | */ 18 | public class MetaData { 19 | 20 | /** The id. */ 21 | @SerializedName("id") 22 | private String id; 23 | 24 | /** The metadata. */ 25 | @SerializedName("metadata") 26 | private Map metadata = new TreeMap(); 27 | 28 | /** 29 | * Gets the id. 30 | * 31 | * @return the id 32 | */ 33 | public String getId() { 34 | return id; 35 | } 36 | 37 | /** 38 | * Sets the id. 39 | * 40 | * @param id the new id 41 | */ 42 | public void setId(String id) { 43 | this.id = id; 44 | } 45 | 46 | /** 47 | * Gets the metadata. 48 | * 49 | * @return the metadata 50 | */ 51 | public Map getMetadata() { 52 | return metadata; 53 | } 54 | 55 | public void setMetaData(String key, String value) { 56 | this.metadata.put(key, value); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/MetaDatas.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | 12 | /** 13 | * The Class MetaDatas. 14 | */ 15 | public class MetaDatas { 16 | 17 | /** The assets. */ 18 | private List metaDatas = new ArrayList(); 19 | 20 | /** 21 | * Gets the metadata. 22 | * 23 | * @return the metadata 24 | */ 25 | public List getMetaDatas() { 26 | return metaDatas; 27 | } 28 | 29 | /** 30 | * Adds the metadata. 31 | * 32 | * @param metadata the metadata 33 | */ 34 | public void addMetaData(MetaData metadata) { 35 | this.metaDatas.add(metadata); 36 | } 37 | 38 | /** 39 | * How many metadata are there 40 | * 41 | * @return the number of metadata 42 | */ 43 | public int size() 44 | { 45 | return metaDatas != null ? metaDatas.size() : 0; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Output.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.bigchaindb.annotations.Exclude; 9 | import com.google.gson.annotations.SerializedName; 10 | 11 | import java.io.Serializable; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | 16 | 17 | /** 18 | * The Class Output. 19 | */ 20 | public class Output implements Serializable { 21 | 22 | /** The output index. */ 23 | @SerializedName("output_index") 24 | @Exclude 25 | private Integer outputIndex; 26 | 27 | /** The transaction id. */ 28 | @SerializedName("transaction_id") 29 | @Exclude 30 | private String transactionId; 31 | 32 | /** The amount. */ 33 | @SerializedName("amount") 34 | private String amount; 35 | 36 | /** The condition. */ 37 | @SerializedName("condition") 38 | private Condition condition; 39 | 40 | /** The public keys. */ 41 | @SerializedName("public_keys") 42 | private List publicKeys = new ArrayList(); 43 | 44 | /** 45 | * Gets the output index. 46 | * 47 | * @return the output index 48 | */ 49 | public Integer getOutputIndex() { 50 | return outputIndex; 51 | } 52 | 53 | /** 54 | * Sets the output index. 55 | * 56 | * @param outputIndex the new output index 57 | */ 58 | public void setOutputIndex(Integer outputIndex) { 59 | this.outputIndex = outputIndex; 60 | } 61 | 62 | /** 63 | * Gets the transaction id. 64 | * 65 | * @return the transaction id 66 | */ 67 | public String getTransactionId() { 68 | return transactionId; 69 | } 70 | 71 | /** 72 | * Sets the transaction id. 73 | * 74 | * @param transactionId the new transaction id 75 | */ 76 | public void setTransactionId(String transactionId) { 77 | this.transactionId = transactionId; 78 | } 79 | 80 | /** 81 | * Gets the amount. 82 | * 83 | * @return the amount 84 | */ 85 | public String getAmount() { 86 | return amount; 87 | } 88 | 89 | /** 90 | * Sets the amount. 91 | * 92 | * @param amount the new amount 93 | */ 94 | public void setAmount(String amount) { 95 | this.amount = amount; 96 | } 97 | 98 | /** 99 | * Gets the condition. 100 | * 101 | * @return the condition 102 | */ 103 | public Condition getCondition() { 104 | return condition; 105 | } 106 | 107 | /** 108 | * Sets the condition. 109 | * 110 | * @param condition the new condition 111 | */ 112 | public void setCondition(Condition condition) { 113 | this.condition = condition; 114 | } 115 | 116 | /** 117 | * Gets the public keys. 118 | * 119 | * @return the public keys 120 | */ 121 | public List getPublicKeys() { 122 | return publicKeys; 123 | } 124 | 125 | /** 126 | * Adds the public key. 127 | * 128 | * @param publicKey the public key 129 | */ 130 | public void addPublicKey(String publicKey){ 131 | this.publicKeys.add(publicKey); 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Outputs.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | 12 | 13 | /** 14 | * The Class Outputs. 15 | */ 16 | public class Outputs { 17 | 18 | /** The output. */ 19 | private List output = new ArrayList(); 20 | 21 | /** 22 | * Gets the output. 23 | * 24 | * @return the output 25 | */ 26 | public List getOutput() { 27 | return output; 28 | } 29 | 30 | /** 31 | * Adds the output. 32 | * 33 | * @param output the output 34 | */ 35 | public void addOutput(Output output) { 36 | this.output.add(output); 37 | } 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Transaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.bigchaindb.annotations.Exclude; 9 | import com.bigchaindb.json.strategy.TransactionIdExclusionStrategy; 10 | import com.bigchaindb.util.JsonUtils; 11 | import com.google.gson.annotations.SerializedName; 12 | 13 | import java.io.Serializable; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | /** 18 | * The Class Transaction. 19 | */ 20 | public class Transaction implements Serializable { 21 | 22 | /** The asset. */ 23 | @SerializedName("asset") 24 | private Asset asset = new Asset(); 25 | 26 | /** The id. */ 27 | @SerializedName("id") 28 | private String id = null; 29 | 30 | /** The inputs. */ 31 | @SerializedName("inputs") 32 | private List inputs = new ArrayList<>(); 33 | 34 | /** The meta data. */ 35 | @SerializedName("metadata") 36 | private Object metaData = null; 37 | 38 | /** The operation. */ 39 | @SerializedName("operation") 40 | private String operation; 41 | 42 | /** The outputs. */ 43 | @SerializedName("outputs") 44 | private List outputs = new ArrayList<>(); 45 | 46 | /** The version. */ 47 | @SerializedName("version") 48 | private String version; 49 | 50 | /** The signed. */ 51 | @Exclude 52 | private Boolean signed; 53 | 54 | /** 55 | * Gets the signed. 56 | * 57 | * @return the signed 58 | */ 59 | public Boolean getSigned() { 60 | return signed; 61 | } 62 | 63 | /** 64 | * Sets the signed. 65 | * 66 | * @param signed the new signed 67 | */ 68 | public void setSigned(Boolean signed) { 69 | this.signed = signed; 70 | } 71 | 72 | /** 73 | * Gets the asset. 74 | * 75 | * @return the asset 76 | */ 77 | public Asset getAsset() { 78 | return asset; 79 | } 80 | 81 | /** 82 | * Sets the asset. 83 | * 84 | * @param asset the new asset 85 | */ 86 | public void setAsset(Asset asset) { 87 | this.asset = asset; 88 | } 89 | 90 | /** 91 | * Gets the id. 92 | * 93 | * @return the id 94 | */ 95 | public String getId() { 96 | return id; 97 | } 98 | 99 | /** 100 | * Sets the id. 101 | * 102 | * @param id the new id 103 | */ 104 | public void setId(String id) { 105 | this.id = id; 106 | } 107 | 108 | /** 109 | * Gets the inputs. 110 | * 111 | * @return the inputs 112 | */ 113 | public List getInputs() { 114 | return inputs; 115 | } 116 | 117 | /** 118 | * Gets the meta data. 119 | * 120 | * @return the meta data 121 | */ 122 | public Object getMetaData() { 123 | return metaData; 124 | } 125 | 126 | /** 127 | * Set the metaData object 128 | * 129 | * @param obj the metadata object 130 | */ 131 | public void setMetaData( Object obj ) 132 | { 133 | this.metaData = obj; 134 | } 135 | 136 | /** 137 | * Gets the operation. 138 | * 139 | * @return the operation 140 | */ 141 | public String getOperation() { 142 | return operation; 143 | } 144 | 145 | /** 146 | * Sets the operation. 147 | * 148 | * @param operation the new operation 149 | */ 150 | public void setOperation(String operation) { 151 | this.operation = operation; 152 | } 153 | 154 | /** 155 | * Gets the outputs. 156 | * 157 | * @return the outputs 158 | */ 159 | public List getOutputs() { 160 | return outputs; 161 | } 162 | 163 | /** 164 | * Gets the version. 165 | * 166 | * @return the version 167 | */ 168 | public String getVersion() { 169 | return version; 170 | } 171 | 172 | /** 173 | * Sets the version. 174 | * 175 | * @param version the new version 176 | */ 177 | public void setVersion(String version) { 178 | this.version = version; 179 | } 180 | 181 | /** 182 | * Adds the input. 183 | * 184 | * @param input the input 185 | */ 186 | public void addInput(Input input) { 187 | this.inputs.add(input); 188 | } 189 | 190 | /** 191 | * Adds the output. 192 | * 193 | * @param output the output 194 | */ 195 | public void addOutput(Output output) { 196 | this.outputs.add(output); 197 | } 198 | 199 | /* (non-Javadoc) 200 | * @see java.lang.Object#toString() 201 | */ 202 | @Override 203 | public String toString() { 204 | return JsonUtils.toJson(this); 205 | } 206 | 207 | /** 208 | * Return the transaction suitable for hashing. 209 | * 210 | * @return the transaction as a json string 211 | */ 212 | public String toHashInput() 213 | { 214 | return JsonUtils.toJson( this, new TransactionIdExclusionStrategy() ); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Transactions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import java.io.Serializable; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | 13 | 14 | /** 15 | * The Class Transactions. 16 | */ 17 | public class Transactions implements Serializable { 18 | 19 | /** The transactions. */ 20 | private List transactions = new ArrayList(); 21 | 22 | /** 23 | * Gets the transactions. 24 | * 25 | * @return the transactions 26 | */ 27 | public List getTransactions() { 28 | return transactions; 29 | } 30 | 31 | /** 32 | * Adds the transaction. 33 | * 34 | * @param transaction the transaction 35 | */ 36 | public void addTransaction(Transaction transaction) { 37 | this.transactions.add(transaction); 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/ValidTransaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | 11 | //{ 12 | // "transaction_id": "", 13 | // "asset_id": "", 14 | // "block_id": "" 15 | //} 16 | 17 | /** 18 | * The Class ValidTransaction. 19 | */ 20 | public class ValidTransaction { 21 | 22 | /** The transaction id. */ 23 | @SerializedName("transaction_id") 24 | private String transactionId; 25 | 26 | /** The asset id. */ 27 | @SerializedName("asset_id") 28 | private String assetId; 29 | 30 | /** The block id. */ 31 | @SerializedName("block_id") 32 | private String blockId; 33 | 34 | /** 35 | * Gets the transaction id. 36 | * 37 | * @return the transaction id 38 | */ 39 | public String getTransactionId() { 40 | return transactionId; 41 | } 42 | 43 | /** 44 | * Gets the asset id. 45 | * 46 | * @return the asset id 47 | */ 48 | public String getAssetId() { 49 | return assetId; 50 | } 51 | 52 | /** 53 | * Gets the block id. 54 | * 55 | * @return the block id 56 | */ 57 | public String getBlockId() { 58 | return blockId; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Validator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | 11 | /** 12 | * The Class Validator. 13 | */ 14 | public class Validator { 15 | 16 | /** 17 | * The public key. 18 | */ 19 | @SerializedName("pub_key") 20 | private ValidatorPubKey pubKey; 21 | 22 | /** 23 | * The signature. 24 | */ 25 | @SerializedName("power") 26 | private Integer power; 27 | 28 | /** 29 | * Gets the pubKey. 30 | * 31 | * @return the pubKey 32 | */ 33 | public ValidatorPubKey getPubKey() { 34 | return pubKey; 35 | } 36 | 37 | /** 38 | * Gets the power. 39 | * 40 | * @return the power 41 | */ 42 | public Integer getPower() { 43 | return power; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/ValidatorPubKey.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | 11 | /** 12 | * The Class ValidatorPubKey. 13 | */ 14 | public class ValidatorPubKey { 15 | 16 | /** 17 | * The data. 18 | */ 19 | @SerializedName("data") 20 | private String data; 21 | 22 | /** 23 | * The type. 24 | */ 25 | @SerializedName("type") 26 | private String type; 27 | 28 | /** 29 | * Gets the data. 30 | * 31 | * @return the data 32 | */ 33 | public String getData() { 34 | return data; 35 | } 36 | 37 | /** 38 | * Gets the type. 39 | * 40 | * @return the type 41 | */ 42 | public String getType() { 43 | return type; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/model/Validators.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.model; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | 12 | /** 13 | * The Class Validators. 14 | */ 15 | public class Validators { 16 | 17 | /** 18 | * The validators. 19 | */ 20 | private List validators = new ArrayList(); 21 | 22 | /** 23 | * Gets the validators. 24 | * 25 | * @return the validators 26 | */ 27 | public List getValidators() { 28 | return validators; 29 | } 30 | 31 | /** 32 | * Adds the validator. 33 | * 34 | * @param validator the validator 35 | */ 36 | public void addValidator(Validator validator) { 37 | this.validators.add(validator); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/util/Base58.java: -------------------------------------------------------------------------------- 1 | /** 2 | * BreadWallet 3 | * Created by Mihail Gutan on mihail@breadwallet.com 11/28/16. 4 | * Copyright (c) 2016 breadwallet LLC 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy 6 | * of this software and associated documentation files (the "Software"), to deal 7 | * in the Software without restriction, including without limitation the rights 8 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | * copies of the Software, and to permit persons to whom the Software is 10 | * furnished to do so, subject to the following conditions: 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | * THE SOFTWARE. 20 | */ 21 | 22 | package com.bigchaindb.util; 23 | 24 | public class Base58 { 25 | 26 | /** 27 | * The Constant ALPHABET. 28 | */ 29 | private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" 30 | .toCharArray(); 31 | 32 | /** 33 | * The Constant BASE_58. 34 | */ 35 | private static final int BASE_58 = ALPHABET.length; 36 | 37 | /** 38 | * The Constant BASE_256. 39 | */ 40 | private static final int BASE_256 = 256; 41 | 42 | /** 43 | * The Constant INDEXES. 44 | */ 45 | private static final int[] INDEXES = new int[128]; 46 | 47 | static { 48 | for (int i = 0; i < INDEXES.length; i++) { 49 | INDEXES[i] = -1; 50 | } 51 | for (int i = 0; i < ALPHABET.length; i++) { 52 | INDEXES[ALPHABET[i]] = i; 53 | } 54 | } 55 | 56 | 57 | /** 58 | * Encode. 59 | * 60 | * @param input the input 61 | * @return the string 62 | */ 63 | public static String encode(byte[] input) { 64 | if (input.length == 0) return ""; 65 | 66 | // 67 | // Make a copy of the input since we are going to modify it. 68 | // 69 | input = copyOfRange(input, 0, input.length); 70 | 71 | // 72 | // Count leading zeroes 73 | // 74 | int zeroCount = 0; 75 | while (zeroCount < input.length && input[zeroCount] == 0) ++zeroCount; 76 | 77 | // 78 | // The actual encoding 79 | // 80 | byte[] temp = new byte[input.length * 2]; 81 | int j = temp.length; 82 | 83 | int startAt = zeroCount; 84 | while (startAt < input.length) { 85 | byte mod = divmod58(input, startAt); 86 | if (input[startAt] == 0) { 87 | ++startAt; 88 | } 89 | 90 | temp[--j] = (byte) ALPHABET[mod]; 91 | } 92 | 93 | // 94 | // Strip extra '1' if any 95 | // 96 | while (j < temp.length && temp[j] == ALPHABET[0]) ++j; 97 | 98 | // 99 | // Add as many leading '1' as there were leading zeros. 100 | // 101 | while (--zeroCount >= 0) temp[--j] = (byte) ALPHABET[0]; 102 | 103 | byte[] output = copyOfRange(temp, j, temp.length); 104 | return new String(output); 105 | } 106 | 107 | /** 108 | * Divmod 58. 109 | * 110 | * @param number the number 111 | * @param startAt the start at 112 | * @return the byte 113 | */ 114 | private static byte divmod58(byte[] number, int startAt) { 115 | int remainder = 0; 116 | for (int i = startAt; i < number.length; i++) { 117 | int digit256 = (int) number[i] & 0xFF; 118 | int temp = remainder * BASE_256 + digit256; 119 | 120 | number[i] = (byte) (temp / BASE_58); 121 | 122 | remainder = temp % BASE_58; 123 | } 124 | 125 | return (byte) remainder; 126 | } 127 | 128 | /** 129 | * Copy of range. 130 | * 131 | * @param source the source 132 | * @param from the from 133 | * @param to the to 134 | * @return the byte[] 135 | */ 136 | private static byte[] copyOfRange(byte[] source, int from, int to) { 137 | byte[] range = new byte[to - from]; 138 | System.arraycopy(source, from, range, 0, range.length); 139 | 140 | return range; 141 | } 142 | 143 | } -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/util/DriverUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.util; 7 | 8 | import com.google.gson.JsonArray; 9 | import com.google.gson.JsonElement; 10 | import com.google.gson.JsonObject; 11 | import com.google.gson.JsonParser; 12 | import org.bouncycastle.jcajce.provider.digest.SHA3; 13 | 14 | import java.util.ArrayList; 15 | import java.util.Collections; 16 | import java.util.List; 17 | 18 | /** 19 | * The Class DriverUtils. 20 | */ 21 | public class DriverUtils { 22 | 23 | /** 24 | * The Constant DIGITS. 25 | */ 26 | private static final char[] DIGITS = 27 | {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 28 | 29 | /** 30 | * Gets the hex. 31 | * 32 | * @param data the data 33 | * @return the hex 34 | */ 35 | public static String getHex(byte[] data) { 36 | final int l = data.length; 37 | final char[] outData = new char[l << 1]; 38 | for (int i = 0, j = 0; i < l; i++) { 39 | outData[j++] = DIGITS[(0xF0 & data[i]) >>> 4]; 40 | outData[j++] = DIGITS[0x0F & data[i]]; 41 | } 42 | 43 | return new String(outData); 44 | } 45 | 46 | /** 47 | * To conform with BigchainDB serialization 48 | * 49 | * @param input the json string to sort the properties for 50 | * @return the json object 51 | */ 52 | public static JsonObject makeSelfSortingGson(String input) { 53 | if (input == null) return null; 54 | 55 | JsonParser jsonParser = new JsonParser(); 56 | return makeSelfSortingGson(jsonParser.parse(input).getAsJsonObject()); 57 | } 58 | 59 | /** 60 | * Make self sorting. 61 | * 62 | * @param input the input 63 | * @return the JSON object 64 | */ 65 | /* 66 | We are using a hack to make stardard org.json be automatically sorted 67 | by key desc alphabetically 68 | */ 69 | public static JsonObject makeSelfSortingGson(JsonObject input) { 70 | if (input == null) return null; 71 | 72 | JsonObject json = new JsonObject(); 73 | 74 | List keys = new ArrayList<>(input.keySet()); 75 | Collections.sort(keys); 76 | for (String key : keys) { 77 | JsonElement j = input.get(key); 78 | if (j instanceof JsonObject) { 79 | json.add(key, makeSelfSortingGson((JsonObject) j)); 80 | } else if (j instanceof JsonArray) { 81 | JsonArray h = (JsonArray) j; 82 | JsonArray oList = new JsonArray(); 83 | for (int i = 0; i < h.size(); i++) { 84 | JsonElement joi = h.get(i); 85 | if (joi instanceof JsonObject) { 86 | oList.add(makeSelfSortingGson((JsonObject) joi)); 87 | json.add(key, oList); 88 | } else { 89 | oList.add(joi); 90 | json.add(key, oList); 91 | } 92 | } 93 | } else { 94 | json.add(key, j); 95 | } 96 | } 97 | 98 | return json; 99 | } 100 | 101 | public static byte[] getSha3HashRaw(byte[] input) { 102 | SHA3.DigestSHA3 md = new SHA3.DigestSHA3(256); //same as DigestSHA3 md = new SHA3.Digest256(); 103 | md.update(input); 104 | return md.digest(); 105 | } 106 | 107 | public static String getSha3HashHex(byte[] input) { 108 | SHA3.DigestSHA3 md = new SHA3.DigestSHA3(256); //same as DigestSHA3 md = new SHA3.Digest256(); 109 | md.update(input); 110 | String id = getHex(md.digest()); 111 | return id; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/util/JsonUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.util; 7 | 8 | import com.bigchaindb.json.factory.GsonEmptyCheckTypeAdapterFactory; 9 | import com.bigchaindb.json.strategy.*; 10 | import com.bigchaindb.model.*; 11 | import com.google.gson.*; 12 | 13 | import java.util.Map; 14 | import java.util.concurrent.ConcurrentHashMap; 15 | import java.util.stream.Stream; 16 | 17 | /** 18 | * Utility class for handling JSON serialization and deserialization. 19 | */ 20 | public class JsonUtils { 21 | 22 | /** 23 | * The gson. 24 | */ 25 | private static String jsonDateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"; 26 | 27 | private static Map typeAdaptersDeserialize = new ConcurrentHashMap(16) {{ 28 | put(Transaction.class.getCanonicalName(), new TypeAdapter(Transaction.class, new TransactionDeserializer())); 29 | put(Transactions.class.getCanonicalName(), new TypeAdapter(Transactions.class, new TransactionsDeserializer())); 30 | put(Assets.class.getCanonicalName(), new TypeAdapter(Assets.class, new AssetsDeserializer())); 31 | put(MetaDatas.class.getCanonicalName(), new TypeAdapter(MetaDatas.class, new MetaDataDeserializer())); 32 | put(Outputs.class.getCanonicalName(), new TypeAdapter(Outputs.class, new OutputsDeserializer())); 33 | put(Validators.class.getCanonicalName(), new TypeAdapter(Validators.class, new ValidatorDeserializer())); 34 | }}; 35 | 36 | private static Map typeAdaptersSerialize = new ConcurrentHashMap(16) {{ 37 | put(Asset.class.getCanonicalName(), new TypeAdapter(Asset.class, new AssetSerializer())); 38 | put(Input.class.getCanonicalName(), new TypeAdapter(Input.class, new InputSerializer())); 39 | put(MetaData.class.getCanonicalName(), new TypeAdapter(MetaData.class, new MetaDataSerializer())); 40 | }}; 41 | 42 | private static synchronized GsonBuilder base() { 43 | GsonBuilder builder = new GsonBuilder(); 44 | 45 | builder = builder 46 | .serializeNulls() 47 | .disableHtmlEscaping() 48 | .setDateFormat(jsonDateFormat) 49 | .registerTypeAdapterFactory(new GsonEmptyCheckTypeAdapterFactory()) 50 | .addSerializationExclusionStrategy(new CustomExclusionStrategy()); 51 | 52 | return builder; 53 | } 54 | 55 | /** 56 | * returns gson 57 | * @return 58 | */ 59 | public static Gson getGson() { 60 | GsonBuilder builder = base(); 61 | 62 | for (TypeAdapter adapter : typeAdaptersDeserialize.values()) { 63 | builder.registerTypeAdapter(adapter.getType(), adapter.getSerializer()); 64 | } 65 | for (TypeAdapter adapter : typeAdaptersSerialize.values()) { 66 | builder.registerTypeAdapter(adapter.getType(), adapter.getSerializer()); 67 | } 68 | 69 | return builder.create(); 70 | } 71 | 72 | /** 73 | * returns gson 74 | * @param exclusionStrategies strategy to use 75 | * @return gson 76 | */ 77 | public static Gson getGson(ExclusionStrategy... exclusionStrategies) { 78 | return getGson(null, exclusionStrategies); 79 | } 80 | 81 | /** 82 | * returns gson 83 | * @param ignoreClass class to ignore 84 | * @param exclusionStrategies strategy to use 85 | * @return gson 86 | */ 87 | public static Gson getGson(Class ignoreClass, ExclusionStrategy... exclusionStrategies) { 88 | GsonBuilder builder = base(); 89 | 90 | for (TypeAdapter adapter : typeAdaptersDeserialize.values()) { 91 | if (!adapter.getType().equals(ignoreClass)) 92 | builder.registerTypeAdapter(adapter.getType(), adapter.getSerializer()); 93 | } 94 | for (TypeAdapter adapter : typeAdaptersSerialize.values()) { 95 | if (!adapter.getType().equals(ignoreClass)) 96 | builder.registerTypeAdapter(adapter.getType(), adapter.getSerializer()); 97 | } 98 | 99 | return builder.setExclusionStrategies(exclusionStrategies).create(); 100 | } 101 | 102 | /** 103 | * Add a type adapter 104 | * 105 | * @param type the type (@Class) we're adapting 106 | * @param jsonDeserializer the type's deserializer 107 | */ 108 | public static void addTypeAdapterDeserializer(Class type, JsonDeserializer jsonDeserializer) { 109 | typeAdaptersDeserialize.put(type.getCanonicalName(), new TypeAdapter(type, jsonDeserializer)); 110 | } 111 | 112 | /** 113 | * Add a type adapter 114 | * 115 | * @param type the type (@Class) we're adapting 116 | * @param jsonSerializer the type's deserializer 117 | */ 118 | public static void addTypeAdapterSerializer(Class type, JsonSerializer jsonSerializer) { 119 | typeAdaptersSerialize.put(type.getCanonicalName(), new TypeAdapter(type, jsonSerializer)); 120 | } 121 | 122 | /** 123 | * From json. 124 | * 125 | * @param the generic type 126 | * @param json the string from which the object is to be deserialized. 127 | * @param T the type of the desired object. 128 | * @return an object of type T from the string. Returns null if json is 129 | * null. 130 | * @see Gson#fromJson(String, Class) 131 | */ 132 | public static T fromJson(String json, Class T) { 133 | return getGson().fromJson(json, T); 134 | } 135 | 136 | /** 137 | * To json. 138 | * 139 | * @param src the object for which Json representation is to be created 140 | * setting for Gson . 141 | * @return Json representation of src. 142 | * @see Gson#toJson(Object) 143 | */ 144 | public static String toJson(Object src) { 145 | return getGson().toJson(src); 146 | } 147 | 148 | /** 149 | * To json. 150 | * @param src the object for which Json representation is to be created 151 | * setting for Gson . 152 | * @return Json representation of src. 153 | * @see Gson#toJson(Object) 154 | */ 155 | public static String toJson(Object src, ExclusionStrategy... exclusionStrategies) { 156 | return getGson(exclusionStrategies).toJson(src); 157 | } 158 | 159 | public static void setJsonDateFormat( final String dateFormat ) { 160 | jsonDateFormat = dateFormat; 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/util/KeyPairUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.util; 7 | 8 | import com.google.api.client.util.Base64; 9 | import net.i2p.crypto.eddsa.EdDSAPrivateKey; 10 | import net.i2p.crypto.eddsa.EdDSAPublicKey; 11 | import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable; 12 | import net.i2p.crypto.eddsa.spec.EdDSAParameterSpec; 13 | import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec; 14 | import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec; 15 | 16 | import java.security.KeyPair; 17 | import java.util.Arrays; 18 | 19 | public class KeyPairUtils { 20 | 21 | public static KeyPair generateNewKeyPair() { 22 | net.i2p.crypto.eddsa.KeyPairGenerator edDsaKpg 23 | = new net.i2p.crypto.eddsa.KeyPairGenerator(); 24 | return edDsaKpg.generateKeyPair(); 25 | } 26 | 27 | /** 28 | * Encodes the public key to base58. 29 | * 30 | * @param publicKey the public key 31 | * @return the string 32 | */ 33 | public static String encodePublicKeyInBase58(EdDSAPublicKey publicKey) { 34 | return Base58.encode(Arrays.copyOfRange(publicKey.getEncoded(), 12, 44)); 35 | } 36 | 37 | public static byte[] encodePrivateKey(KeyPair keyPair) { 38 | return keyPair.getPrivate().getEncoded(); 39 | } 40 | 41 | public static String encodePrivateKeyBase64(KeyPair keyPair) { 42 | return Base64.encodeBase64String(encodePrivateKey(keyPair)); 43 | } 44 | 45 | public static KeyPair decodeKeyPair(byte[] encodedPrivateKey) { 46 | EdDSAParameterSpec keySpecs = EdDSANamedCurveTable.getByName("Ed25519"); 47 | byte[] seed = Arrays.copyOfRange(encodedPrivateKey, 16, 48); 48 | EdDSAPrivateKeySpec privKeySpec = new EdDSAPrivateKeySpec(seed, keySpecs); 49 | EdDSAPublicKeySpec pubKeySpec = new EdDSAPublicKeySpec(privKeySpec.getA(), keySpecs); 50 | return new KeyPair(new EdDSAPublicKey(pubKeySpec), new EdDSAPrivateKey(privKeySpec)); 51 | } 52 | 53 | public static KeyPair decodeKeyPair(String encodedPrivateKeyBase64) { 54 | return decodeKeyPair(Base64.decodeBase64(encodedPrivateKeyBase64)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/util/NetworkUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.util; 7 | 8 | import okhttp3.*; 9 | import okio.Buffer; 10 | 11 | import java.io.IOException; 12 | 13 | import com.bigchaindb.model.BigChainDBGlobals; 14 | import com.bigchaindb.model.GenericCallback; 15 | 16 | 17 | /** 18 | * The Class NetworkUtils. 19 | */ 20 | public class NetworkUtils { 21 | 22 | /** 23 | * The Constant JSON. 24 | * 25 | * @param url the url 26 | * @param body the body 27 | * @param callback the callback 28 | */ 29 | 30 | private static String bodyToString(final Request request){ 31 | 32 | try { 33 | final Request copy = request.newBuilder().build(); 34 | final Buffer buffer = new Buffer(); 35 | copy.body().writeTo(buffer); 36 | return buffer.readUtf8(); 37 | } catch (final IOException e) { 38 | return "did not work"; 39 | } 40 | } 41 | /** 42 | * Send post request. 43 | * 44 | * @param url the url 45 | * @param body the body 46 | * @param callback the callback 47 | */ 48 | public static void sendPostRequest(String url, RequestBody body, 49 | final GenericCallback callback) { 50 | 51 | Request request = new Request.Builder().url(url).post(body).build(); 52 | 53 | BigChainDBGlobals.getHttpClient().newCall(request).enqueue(new Callback() { 54 | @Override 55 | public void onFailure(Call call, IOException e) { 56 | BigChainDBGlobals.setConnected(false); 57 | 58 | } 59 | 60 | @Override 61 | public void onResponse(Call call, Response response) { 62 | if (response.code() == 202) callback.pushedSuccessfully(response); 63 | else if (response.code() == 400) callback.transactionMalformed(response); 64 | else callback.otherError(response); 65 | BigChainDBGlobals.setConnected(true); 66 | response.close(); 67 | } 68 | }); 69 | } 70 | 71 | /** 72 | * Send post request. 73 | * 74 | * @param url the url 75 | * @param body the body 76 | * @return the response 77 | * @throws IOException Signals that an I/O exception has occurred. 78 | */ 79 | public static Response sendPostRequest(String url, RequestBody body) throws IOException { 80 | Response response = null; 81 | 82 | try{ 83 | Request request = new Request.Builder().url(url).post(body).build(); 84 | response = BigChainDBGlobals.getHttpClient().newCall(request).execute(); 85 | BigChainDBGlobals.setConnected(true); 86 | } 87 | catch(IOException e) { 88 | BigChainDBGlobals.setConnected(false); 89 | throw new IOException(); 90 | } 91 | 92 | return response; 93 | } 94 | 95 | /** 96 | * Send get request. 97 | * 98 | * @param url the url 99 | * @return the response 100 | * @throws IOException Signals that an I/O exception has occurred. 101 | */ 102 | public static Response sendGetRequest(String url) throws IOException { 103 | Response response = null; 104 | 105 | try{ 106 | Request request = new Request.Builder().url(url).get().build(); 107 | response = BigChainDBGlobals.getHttpClient().newCall(request).execute(); 108 | BigChainDBGlobals.setConnected(true); 109 | } 110 | catch(IOException e) { 111 | BigChainDBGlobals.setConnected(false); 112 | throw new IOException(); 113 | } 114 | 115 | return response; 116 | 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/util/ScannerUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.util; 7 | 8 | import java.util.Scanner; 9 | 10 | 11 | /** 12 | * The Class ScannerUtil. 13 | */ 14 | public class ScannerUtil { 15 | 16 | /** 17 | * exit when enter string "exit". 18 | */ 19 | public static void monitorExit() { 20 | try (Scanner scanner = new Scanner(System.in)) { 21 | while (true) if ("exit" .equals(scanner.nextLine())) break; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/util/TypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.util; 7 | 8 | import com.google.gson.JsonDeserializer; 9 | import com.google.gson.JsonSerializer; 10 | 11 | /** 12 | * container for storing type sdapter information 13 | */ 14 | public class TypeAdapter 15 | { 16 | private Class type; 17 | private Object serializer; 18 | 19 | /** 20 | * Contruct a type adapter 21 | * 22 | * @param type the class 23 | * @param serializer its serializer 24 | */ 25 | TypeAdapter( Class type, JsonDeserializer serializer ) 26 | { 27 | this.type = type; 28 | this.serializer = serializer; 29 | } 30 | 31 | /** 32 | * Contruct a type adapter 33 | * 34 | * @param type the class 35 | * @param serializer its serializer 36 | */ 37 | TypeAdapter( Class type, JsonSerializer serializer ) 38 | { 39 | this.type = type; 40 | this.serializer = serializer; 41 | } 42 | 43 | /** 44 | * Get the deserializer 45 | * 46 | * @return the deserializer 47 | */ 48 | public Object getSerializer() 49 | { 50 | return this.serializer; 51 | } 52 | 53 | /** 54 | * Get the class for the deserializer 55 | * 56 | * @return the class 57 | */ 58 | public Class getType() 59 | { 60 | return type; 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/ws/BigchainDbWSSessionManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.ws; 7 | 8 | import java.net.URI; 9 | 10 | import javax.websocket.ClientEndpoint; 11 | import javax.websocket.CloseReason; 12 | import javax.websocket.ContainerProvider; 13 | import javax.websocket.OnClose; 14 | import javax.websocket.OnMessage; 15 | import javax.websocket.OnOpen; 16 | import javax.websocket.Session; 17 | import javax.websocket.WebSocketContainer; 18 | 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | import com.bigchaindb.util.ScannerUtil; 23 | 24 | /** 25 | * The Class BigchainDbWSSessionManager. 26 | */ 27 | @ClientEndpoint 28 | public class BigchainDbWSSessionManager { 29 | 30 | private static final Logger log = LoggerFactory.getLogger( BigchainDbWSSessionManager.class ); 31 | 32 | /** The user session. */ 33 | private Session userSession = null; 34 | 35 | /** The message handler. */ 36 | private MessageHandler messageHandler; 37 | 38 | /** 39 | * Instantiates a new bigchain db WS session manager. 40 | * 41 | * @param endpointURI the endpoint URI 42 | * @param messageHandler the message handler 43 | */ 44 | public BigchainDbWSSessionManager(URI endpointURI, MessageHandler messageHandler) { 45 | try { 46 | 47 | WebSocketContainer container = ContainerProvider.getWebSocketContainer(); 48 | container.setDefaultMaxSessionIdleTimeout(-1); 49 | this.messageHandler = messageHandler; 50 | container.connectToServer(this, endpointURI); 51 | ScannerUtil.monitorExit(); 52 | } catch (Exception e) { 53 | throw new RuntimeException(e); 54 | } 55 | } 56 | 57 | /** 58 | * Callback hook for Connection open events. 59 | * 60 | * @param userSession 61 | * the userSession which is opened. 62 | */ 63 | @OnOpen 64 | public void onOpen(Session userSession) { 65 | log.debug( "Opening Websocket" ); 66 | this.userSession = userSession; 67 | } 68 | 69 | /** 70 | * Callback hook for Connection close events. 71 | * 72 | * @param userSession 73 | * the userSession which is getting closed. 74 | * @param reason 75 | * the reason for connection close 76 | */ 77 | @OnClose 78 | public void onClose(Session userSession, CloseReason reason) { 79 | log.debug( "Closing Websocket" ); 80 | this.userSession = null; 81 | } 82 | 83 | /** 84 | * Callback hook for Message Events. This method will be invoked when a 85 | * client send a message. 86 | * 87 | * @param message 88 | * The text message 89 | */ 90 | @OnMessage 91 | public void onMessage(String message) { 92 | log.debug( message ); 93 | if (this.messageHandler != null) { 94 | this.messageHandler.handleMessage(message); 95 | } 96 | } 97 | 98 | /** 99 | * register message handler. 100 | * 101 | * @param msgHandler the msg handler 102 | */ 103 | public void addMessageHandler(MessageHandler msgHandler) { 104 | this.messageHandler = msgHandler; 105 | } 106 | 107 | /** 108 | * Send a message. 109 | * 110 | * @param message the message 111 | */ 112 | public void sendMessage(String message) { 113 | this.userSession.getAsyncRemote().sendText(message); 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/com/bigchaindb/ws/MessageHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.ws; 7 | 8 | 9 | /** 10 | * The Interface MessageHandler. 11 | */ 12 | public interface MessageHandler { 13 | 14 | /** 15 | * Handle message. 16 | * 17 | * @param message the message 18 | */ 19 | public void handleMessage(String message); 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/AbstractTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb; 7 | 8 | import java.io.FileInputStream; 9 | import java.io.FileNotFoundException; 10 | import java.io.IOException; 11 | import java.io.InputStream; 12 | import java.net.MalformedURLException; 13 | import java.net.URL; 14 | import java.util.Map; 15 | import java.util.Properties; 16 | import java.util.UUID; 17 | 18 | import com.bigchaindb.model.Transaction; 19 | 20 | /** 21 | * Test scaffolding and configuration 22 | * 23 | * With respect to test.properties: 24 | * 25 | * There is a default test.properties file in test/resources 26 | * If you wish to use different properties you can set the environment variable "BDB_DRIVER_PROPERTIES" to point to a file, the 27 | * easiest thing is to copy the test/resoruces/test.properties to a file on your local filesystem and change the appropriate properties. 28 | * When specifying a file on the local file system prefix the file with "file:///" 29 | * The property file on a filesystem should be constructed as an URL, 30 | * for the property file in C:\Test\test.properties the environment variable would be set to: file:///C:/Test/test.properties for Windows 31 | * on Unix if the file is in /usr/local/test/test.properties it would be set to file:///usr/local/test/test.properties 32 | * 33 | */ 34 | public abstract class AbstractTest 35 | { 36 | private static Map env = System.getenv(); 37 | private static Properties properties = initProperties(); 38 | private static final String bdbDriverProperties = "BDB_DRIVER_PROPERTIES"; 39 | 40 | /** 41 | * Initialize the properties file 42 | * 43 | * @return initialized properties 44 | * @throws RuntimeException no point in continuing if the properties file cannot be found 45 | */ 46 | private static Properties initProperties() throws RuntimeException 47 | { 48 | Properties props = new Properties(); 49 | 50 | try( InputStream input = new FileInputStream( getInputFile( bdbDriverProperties, "test.properties" ) )) { 51 | props.load( input ); 52 | } catch( FileNotFoundException ex ) { 53 | System.err.println( "cannot find test.properties, set environment variable test.properties with path name to a test properties file" ); 54 | throw new RuntimeException( "cannot find test.properties, set environment variable test.properties with path name to a test properties file", ex ); 55 | } catch( IOException ex ) { 56 | throw new RuntimeException( "Error reading properties files " + env.getOrDefault( bdbDriverProperties, "test.properties" ), ex ); 57 | } 58 | 59 | return props; 60 | } 61 | 62 | /** 63 | * Get the input file, a property file on the filesystem should be constructed as an URL, 64 | * for the property file in C:\Test\test.properties the environment variable would be set to: file:///C:/Test/test.properties for Windows 65 | * on Unix if the file is in /usr/local/test/test.properties it would be set to file:///usr/local/test/test.properties 66 | * 67 | * @param envKey the env variable with the file path to the properties file 68 | * @param otherwise the default properties file on the classpath 69 | * @return a url file name as a @String 70 | */ 71 | private static String getInputFile( final String envKey, final String otherwise ) 72 | { 73 | String propertiesFile = env.getOrDefault( envKey, otherwise ); 74 | 75 | URL url = null; 76 | if( propertiesFile.startsWith( "file:///" ) ) { 77 | try { 78 | url = new URL( propertiesFile ); 79 | return url.getFile(); 80 | } catch( MalformedURLException ex ) { 81 | System.err.println( "Error with properties file MalformedURLException " + propertiesFile + " Falling back to " + otherwise ); 82 | System.err.println( ex.getMessage() ); 83 | propertiesFile = otherwise; 84 | } 85 | } 86 | 87 | url = Thread.currentThread().getContextClassLoader().getResource( propertiesFile ); 88 | return url.getFile(); 89 | } 90 | 91 | /** 92 | * Get a property value as a String 93 | * @param key the property 94 | * @param otherwise the value if it doesn't exist 95 | * @return the value or otherwise 96 | */ 97 | protected static String get( final String key, final String otherwise ) 98 | { 99 | return properties.getProperty( key, otherwise ); 100 | } 101 | 102 | /** 103 | * get a property as an int 104 | * 105 | * @param key the property 106 | * @param otherwise the value if it doesn't exist 107 | * @return the value or otherwise 108 | */ 109 | protected static int getInt( final String key, final int otherwise ) 110 | { 111 | try { 112 | return Integer.parseInt( properties.getProperty( key ) ); 113 | } catch( Exception ex ) { 114 | return otherwise; 115 | } 116 | } 117 | 118 | /** 119 | * get system environment variable 120 | * 121 | * @param envKey environment variable name to fetch 122 | * @param otherwise value if not set 123 | * @return the value or otherwise 124 | */ 125 | protected static String getEnv( final String envKey, final String otherwise ) 126 | { 127 | return env.getOrDefault( envKey, otherwise ); 128 | } 129 | 130 | /** 131 | * Wrap exact searches in quotes 132 | * 133 | * @param stringToQuote to be quoted 134 | * @return the quoted string 135 | */ 136 | protected static String asQuoted( final String stringToQuote ) 137 | { 138 | return "\"" + stringToQuote + "\""; 139 | } 140 | 141 | /** 142 | * Get a unique ID 143 | * 144 | * @return @UUID as a @String 145 | */ 146 | protected static String getUUID() 147 | { 148 | return UUID.randomUUID().toString(); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/api/AbstractApiTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import com.bigchaindb.AbstractTest; 9 | import com.bigchaindb.builders.BigchainDbConfigBuilder; 10 | import com.bigchaindb.model.ApiEndpoints; 11 | import com.bigchaindb.model.BigChainDBGlobals; 12 | import com.bigchaindb.model.Connection; 13 | import com.bigchaindb.util.JsonUtils; 14 | import com.bigchaindb.ws.MessageHandler; 15 | 16 | import org.junit.AfterClass; 17 | import org.junit.BeforeClass; 18 | import org.junit.Test; 19 | 20 | import static com.bigchaindb.api.AssetsApiTest.V1_ASSET_JSON; 21 | import static com.bigchaindb.api.AssetsApiTest.V1_ASSET_LIMIT_JSON; 22 | import static com.bigchaindb.api.BlocksApiTest.V1_BLOCK_BY_TRANS_JSON; 23 | import static com.bigchaindb.api.BlocksApiTest.V1_BLOCK_JSON; 24 | import static com.bigchaindb.api.MetaDataApiTest.V1_METADATA_JSON; 25 | import static com.bigchaindb.api.MetaDataApiTest.V1_METADATA_LIMIT_JSON; 26 | import static com.bigchaindb.api.OutputsApiTest.*; 27 | import static com.bigchaindb.api.TransactionCreateApiTest.*; 28 | import static com.bigchaindb.api.ValidatorsApiTest.V1_VALIDATORS_JSON; 29 | import static net.jadler.Jadler.*; 30 | import static org.junit.Assert.assertTrue; 31 | 32 | import java.util.ArrayList; 33 | import java.util.HashMap; 34 | import java.util.List; 35 | import java.util.Map; 36 | import java.util.concurrent.TimeoutException; 37 | 38 | public class AbstractApiTest extends AbstractTest { 39 | 40 | public static String V1_JSON = "{\n" + 41 | " \"assets\": \"/assets/\",\n" + 42 | " \"docs\": \"https://docs.bigchaindb.com/projects/server/en/v2.0.0b2/http-client-server-api.html\",\n" + 43 | " \"metadata\": \"/metadata/\",\n" + 44 | " \"outputs\": \"/outputs/\",\n" + 45 | " \"streams\": \"ws://localhost:9985/api/v1/streams/valid_transactions\",\n" + 46 | " \"transactions\": \"/transactions/\",\n" + 47 | " \"validators\": \"/validators\"\n" + 48 | "}"; 49 | 50 | /** 51 | * Inits the. 52 | * @throws TimeoutException 53 | */ 54 | @BeforeClass 55 | public static void init() throws TimeoutException { 56 | initJadler(); 57 | onRequest() 58 | .havingMethodEqualTo("GET") 59 | .havingPathEqualTo("/api/v1") 60 | .respond() 61 | .withBody(V1_JSON) 62 | .withStatus(200); 63 | onRequest() 64 | .havingMethodEqualTo("GET") 65 | .havingPathEqualTo("/api/v1/validators") 66 | .respond() 67 | .withBody(V1_VALIDATORS_JSON) 68 | .withStatus(200); 69 | onRequest() 70 | .havingMethodEqualTo("GET") 71 | .havingPathEqualTo("/api/v1/assets/") 72 | .havingParameterEqualTo("search", "bigchaindb") 73 | .respond() 74 | .withBody(V1_ASSET_JSON) 75 | .withStatus(200); 76 | onRequest() 77 | .havingMethodEqualTo("GET") 78 | .havingPathEqualTo("/api/v1/assets/") 79 | .havingParameterEqualTo("search", "bigchaindb") 80 | .havingParameterEqualTo("limit", "2") 81 | .respond() 82 | .withBody(V1_ASSET_LIMIT_JSON) 83 | .withStatus(200); 84 | onRequest() 85 | .havingMethodEqualTo("GET") 86 | .havingPathEqualTo("/api/v1/metadata/") 87 | .havingParameterEqualTo("search", "bigchaindb") 88 | .respond() 89 | .withBody(V1_METADATA_JSON) 90 | .withStatus(200); 91 | onRequest() 92 | .havingMethodEqualTo("GET") 93 | .havingPathEqualTo("/api/v1/metadata/") 94 | .havingParameterEqualTo("search", "bigchaindb") 95 | .havingParameterEqualTo("limit", "2") 96 | .respond() 97 | .withBody(V1_METADATA_LIMIT_JSON) 98 | .withStatus(200); 99 | onRequest() 100 | .havingMethodEqualTo("GET") 101 | .havingPathEqualTo("/api/v1/blocks/1") 102 | .respond() 103 | .withBody(V1_BLOCK_JSON) 104 | .withStatus(200); 105 | onRequest() 106 | .havingMethodEqualTo("GET") 107 | .havingPathEqualTo("/api/v1/blocks") 108 | .havingParameterEqualTo("transaction_id", "4957744b3ac54434b8270f2c854cc1040228c82ea4e72d66d2887a4d3e30b317") 109 | .respond() 110 | .withBody(V1_BLOCK_BY_TRANS_JSON) 111 | .withStatus(200); 112 | onRequest() 113 | .havingMethodEqualTo("GET") 114 | .havingPathEqualTo("/api/v1/outputs") 115 | .havingParameterEqualTo("public_key", PUBKEY) 116 | .respond() 117 | .withBody(V1_OUTPUTS_JSON) 118 | .withStatus(200); 119 | onRequest() 120 | .havingMethodEqualTo("GET") 121 | .havingPathEqualTo("/api/v1/outputs") 122 | .havingParameterEqualTo("public_key", PUBKEY) 123 | .havingParameterEqualTo("spent", "true") 124 | .respond() 125 | .withBody(V1_OUTPUTS_SPENT_JSON) 126 | .withStatus(200); 127 | onRequest() 128 | .havingMethodEqualTo("GET") 129 | .havingPathEqualTo("/api/v1/outputs") 130 | .havingParameterEqualTo("public_key", PUBKEY) 131 | .havingParameterEqualTo("spent", "false") 132 | .respond() 133 | .withBody(V1_OUTPUTS_UNSPENT_JSON) 134 | .withStatus(200); 135 | onRequest() 136 | .havingMethodEqualTo("GET") 137 | .havingPathEqualTo("/api/v1/transactions/" + TRANSACTION_ID) 138 | .respond() 139 | .withBody(V1_GET_TRANSACTION_JSON) 140 | .withStatus(200); 141 | onRequest() 142 | .havingMethodEqualTo("GET") 143 | .havingPathEqualTo("/api/v1/transactions") 144 | .havingParameterEqualTo("asset_id", TRANSACTION_ID) 145 | .havingParameterEqualTo("operation", "TRANSFER") 146 | .respond() 147 | .withBody(V1_GET_TRANSACTION_BY_ASSETS_JSON) 148 | .withStatus(200); 149 | onRequest() 150 | .havingMethodEqualTo("POST") 151 | .havingPathEqualTo("/api/v1/transactions") 152 | .respond() 153 | .withBody(V1_POST_TRANSACTION_JSON) 154 | .withStatus(200); 155 | JsonUtils.setJsonDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); 156 | 157 | Map connConfig = new HashMap(); 158 | List connections = new ArrayList(); 159 | Map headers = new HashMap(); 160 | 161 | //define headers 162 | headers.put("app_id", "2bbaf3ff"); 163 | headers.put("app_key", "c929b708177dcc8b9d58180082029b8d"); 164 | 165 | connConfig.put("baseUrl", "http://localhost:" + port()); 166 | connConfig.put("headers", headers); 167 | Connection conn1 = new Connection(connConfig); 168 | connections.add(conn1); 169 | BigchainDbConfigBuilder 170 | .addConnections(connections) 171 | .webSocketMonitor(new MessageHandler() { 172 | @Override 173 | public void handleMessage(String message) { 174 | } 175 | }) 176 | .setup(); 177 | } 178 | 179 | @AfterClass 180 | public static void tearDown() { 181 | closeJadler(); 182 | } 183 | 184 | /** 185 | * Test db globals. 186 | */ 187 | @Test 188 | public void testBigChainDBGlobals() { 189 | assertTrue(BigChainDBGlobals.getWsSocketUrl().endsWith("/api/v1/streams/valid_transactions")); 190 | assertTrue(BigChainDBGlobals.getAuthorizationTokens().get("app_id").equals("2bbaf3ff")); 191 | assertTrue(BigChainDBGlobals.getAuthorizationTokens().get("app_key").equals("c929b708177dcc8b9d58180082029b8d")); 192 | } 193 | 194 | /** 195 | * Test api endpoints. 196 | */ 197 | @Test 198 | public void testApiEndpoints() { 199 | ApiEndpoints api = BigChainDBGlobals.getApiEndpoints(); 200 | assertTrue(api.getAssets().equals("/assets/")); 201 | assertTrue(api.getDocs().equals("https://docs.bigchaindb.com/projects/server/en/v2.0.0b2/http-client-server-api.html")); 202 | assertTrue(api.getMetadata().equals("/metadata/")); 203 | assertTrue(api.getOutputs().equals("/outputs/")); 204 | assertTrue(api.getStreams().equals("ws://localhost:9985/api/v1/streams/valid_transactions")); 205 | assertTrue(api.getTransactions().equals("/transactions/")); 206 | assertTrue(api.getValidators().equals("/validators")); 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/api/AccountApiTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import org.junit.Test; 9 | 10 | import com.bigchaindb.api.AccountApi; 11 | import com.bigchaindb.model.Account; 12 | import com.bigchaindb.model.Assets; 13 | 14 | import java.io.IOException; 15 | import java.security.KeyPair; 16 | import java.security.spec.InvalidKeySpecException; 17 | 18 | import static org.junit.Assert.assertTrue; 19 | 20 | /** 21 | * The Class AccountApiTest. 22 | */ 23 | public class AccountApiTest extends AbstractApiTest { 24 | 25 | private static final String publicKey = "302a300506032b657003210033c43dc2180936a2a9138a05f06c892d2fb1cfda4562cbc35373bf13cd8ed373"; 26 | private static final String privateKey = "302e020100300506032b6570042204206f6b0cd095f1e83fc5f08bffb79c7c8a30e77a3ab65f4bc659026b76394fcea8"; 27 | 28 | /** 29 | * Test asset search. 30 | */ 31 | @Test 32 | public void testAssetSearch() { 33 | try { 34 | Account account = AccountApi.loadAccount(publicKey, privateKey); 35 | assertTrue(account.getPublicKey() != null); 36 | assertTrue(account.getPrivateKey() != null); 37 | } catch (InvalidKeySpecException e1) { 38 | // TODO Auto-generated catch block 39 | e1.printStackTrace(); 40 | } 41 | } 42 | 43 | /** 44 | * Test create account. 45 | */ 46 | @Test 47 | public void testCreateAccount() { 48 | Account account = AccountApi.createAccount(); 49 | assertTrue(account.getPublicKey() != null); 50 | assertTrue(account.getPrivateKey() != null); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/api/AssetsApiTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import static org.junit.Assert.assertTrue; 9 | 10 | import java.io.IOException; 11 | import java.security.KeyPair; 12 | import java.util.Map; 13 | import java.util.TreeMap; 14 | 15 | import com.bigchaindb.api.AssetsApi; 16 | import com.bigchaindb.builders.BigchainDbTransactionBuilder; 17 | import com.bigchaindb.model.Assets; 18 | import com.bigchaindb.model.Transaction; 19 | 20 | import net.i2p.crypto.eddsa.EdDSAPrivateKey; 21 | import net.i2p.crypto.eddsa.EdDSAPublicKey; 22 | import org.junit.Test; 23 | 24 | import static org.junit.Assert.assertEquals; 25 | 26 | /** 27 | * The Class AssetsApiTest. 28 | */ 29 | public class AssetsApiTest extends AbstractApiTest { 30 | 31 | public static String V1_ASSET_JSON = "[\n" + 32 | " {\n" + 33 | " \"data\": {\"msg\": \"Hello BigchainDB 1!\"},\n" + 34 | " \"id\": \"51ce82a14ca274d43e4992bbce41f6fdeb755f846e48e710a3bbb3b0cf8e4204\"\n" + 35 | " },\n" + 36 | " {\n" + 37 | " \"data\": {\"msg\": \"Hello BigchainDB 2!\"},\n" + 38 | " \"id\": \"b4e9005fa494d20e503d916fa87b74fe61c079afccd6e084260674159795ee31\"\n" + 39 | " },\n" + 40 | " {\n" + 41 | " \"data\": {\"msg\": \"Hello BigchainDB 3!\"},\n" + 42 | " \"id\": \"fa6bcb6a8fdea3dc2a860fcdc0e0c63c9cf5b25da8b02a4db4fb6a2d36d27791\"\n" + 43 | " }\n" + 44 | "]"; 45 | 46 | public static String V1_ASSET_LIMIT_JSON = "[\n" + 47 | " {\n" + 48 | " \"data\": {\"msg\": \"Hello BigchainDB 1!\"},\n" + 49 | " \"id\": \"51ce82a14ca274d43e4992bbce41f6fdeb755f846e48e710a3bbb3b0cf8e4204\"\n" + 50 | " },\n" + 51 | " {\n" + 52 | " \"data\": {\"msg\": \"Hello BigchainDB 2!\"},\n" + 53 | " \"id\": \"b4e9005fa494d20e503d916fa87b74fe61c079afccd6e084260674159795ee31\"\n" + 54 | " }\n" + 55 | "]"; 56 | 57 | /** 58 | * Test asset search. 59 | */ 60 | @Test 61 | public void testAssetSearch() { 62 | try { 63 | Assets assets = AssetsApi.getAssets("bigchaindb"); 64 | assertTrue(assets.size() == 3); 65 | assertTrue(assets.getAssets().get(0).getId().equals("51ce82a14ca274d43e4992bbce41f6fdeb755f846e48e710a3bbb3b0cf8e4204")); 66 | } catch (IOException e) { 67 | e.printStackTrace(); 68 | } 69 | } 70 | 71 | /** 72 | * Test asset search with limit. 73 | */ 74 | @Test 75 | public void testAssetSearchWithLimit() { 76 | try { 77 | Assets assets = AssetsApi.getAssetsWithLimit("bigchaindb", "2"); 78 | assertTrue(assets.size() == 2); 79 | } catch (IOException e) { 80 | e.printStackTrace(); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/api/BlocksApiTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import org.junit.Ignore; 9 | import org.junit.Test; 10 | 11 | import com.bigchaindb.api.BlocksApi; 12 | import com.bigchaindb.model.Block; 13 | 14 | import java.io.IOException; 15 | import java.util.List; 16 | 17 | import static org.junit.Assert.assertTrue; 18 | 19 | /** 20 | * The Class BlocksApiTest. 21 | */ 22 | public class BlocksApiTest extends AbstractApiTest { 23 | 24 | public static String V1_BLOCK_JSON = "{\n" + 25 | " \"height\": 1,\n" + 26 | " \"transactions\": [\n" + 27 | " {\n" + 28 | " \"asset\": {\n" + 29 | " \"data\": {\n" + 30 | " \"msg\": \"Hello BigchainDB!\"\n" + 31 | " }\n" + 32 | " },\n" + 33 | " \"id\": \"4957744b3ac54434b8270f2c854cc1040228c82ea4e72d66d2887a4d3e30b317\",\n" + 34 | " \"inputs\": [\n" + 35 | " {\n" + 36 | " \"fulfillment\": \"pGSAIDE5i63cn4X8T8N1sZ2mGkJD5lNRnBM4PZgI_zvzbr-cgUCy4BR6gKaYT-tdyAGPPpknIqI4JYQQ-p2nCg3_9BfOI-15vzldhyz-j_LZVpqAlRmbTzKS-Q5gs7ZIFaZCA_UD\",\n" + 37 | " \"fulfills\": null,\n" + 38 | " \"owners_before\": [\n" + 39 | " \"4K9sWUMFwTgaDGPfdynrbxWqWS6sWmKbZoTjxLtVUibD\"\n" + 40 | " ]\n" + 41 | " }\n" + 42 | " ],\n" + 43 | " \"metadata\": {\n" + 44 | " \"sequence\": 0\n" + 45 | " },\n" + 46 | " \"operation\": \"CREATE\",\n" + 47 | " \"outputs\": [\n" + 48 | " {\n" + 49 | " \"amount\": \"1\",\n" + 50 | " \"condition\": {\n" + 51 | " \"details\": {\n" + 52 | " \"public_key\": \"4K9sWUMFwTgaDGPfdynrbxWqWS6sWmKbZoTjxLtVUibD\",\n" + 53 | " \"type\": \"ed25519-sha-256\"\n" + 54 | " },\n" + 55 | " \"uri\": \"ni:///sha-256;PNYwdxaRaNw60N6LDFzOWO97b8tJeragczakL8PrAPc?fpt=ed25519-sha-256&cost=131072\"\n" + 56 | " },\n" + 57 | " \"public_keys\": [\n" + 58 | " \"4K9sWUMFwTgaDGPfdynrbxWqWS6sWmKbZoTjxLtVUibD\"\n" + 59 | " ]\n" + 60 | " }\n" + 61 | " ],\n" + 62 | " \"version\": \"2.0\"\n" + 63 | " }\n" + 64 | " ]\n" + 65 | "}"; 66 | 67 | public static String V1_BLOCK_BY_TRANS_JSON = "[\n" + 68 | " 1\n" + 69 | "]"; 70 | 71 | 72 | /** 73 | * Test get block. 74 | */ 75 | @Test @Ignore 76 | public void testGetBlock() { 77 | try { 78 | Block block = BlocksApi.getBlock("1"); 79 | assertTrue(block.getHeight() == 1); 80 | assertTrue(block.getTransactions().size() == 1); 81 | } catch (IOException e) { 82 | e.printStackTrace(); 83 | } 84 | } 85 | 86 | /** 87 | * Test get block. 88 | */ 89 | @Test 90 | public void testGetBlockByTransactionId() { 91 | try { 92 | List list = BlocksApi.getBlocksByTransactionId("4957744b3ac54434b8270f2c854cc1040228c82ea4e72d66d2887a4d3e30b317"); 93 | assertTrue(list.size() == 1); 94 | assertTrue(list.get(0).equals("1")); 95 | } catch (IOException e) { 96 | e.printStackTrace(); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/api/MetaDataApiTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import org.junit.Test; 9 | 10 | import com.bigchaindb.api.MetaDataApi; 11 | import com.bigchaindb.model.Assets; 12 | import com.bigchaindb.model.MetaDatas; 13 | 14 | import java.io.IOException; 15 | 16 | import static org.junit.Assert.assertTrue; 17 | 18 | /** 19 | * The Class AssetsApiTest. 20 | */ 21 | public class MetaDataApiTest extends AbstractApiTest { 22 | 23 | public static String V1_METADATA_JSON = "[\n" + 24 | " {\n" + 25 | " \"metadata\": {\"metakey1\": \"Hello BigchainDB 1!\"},\n" + 26 | " \"id\": \"51ce82a14ca274d43e4992bbce41f6fdeb755f846e48e710a3bbb3b0cf8e4204\"\n" + 27 | " },\n" + 28 | " {\n" + 29 | " \"metadata\": {\"metakey2\": \"Hello BigchainDB 2!\"},\n" + 30 | " \"id\": \"b4e9005fa494d20e503d916fa87b74fe61c079afccd6e084260674159795ee31\"\n" + 31 | " },\n" + 32 | " {\n" + 33 | " \"metadata\": {\"metakey3\": \"Hello BigchainDB 3!\"},\n" + 34 | " \"id\": \"fa6bcb6a8fdea3dc2a860fcdc0e0c63c9cf5b25da8b02a4db4fb6a2d36d27791\"\n" + 35 | " }\n" + 36 | "]\n"; 37 | 38 | public static String V1_METADATA_LIMIT_JSON = "[\n" + 39 | " {\n" + 40 | " \"metadata\": {\"msg\": \"Hello BigchainDB 1!\"},\n" + 41 | " \"id\": \"51ce82a14ca274d43e4992bbce41f6fdeb755f846e48e710a3bbb3b0cf8e4204\"\n" + 42 | " },\n" + 43 | " {\n" + 44 | " \"metadata\": {\"msg\": \"Hello BigchainDB 2!\"},\n" + 45 | " \"id\": \"b4e9005fa494d20e503d916fa87b74fe61c079afccd6e084260674159795ee31\"\n" + 46 | " }\n" + 47 | "]"; 48 | 49 | /** 50 | * Test metadata search. 51 | */ 52 | @Test 53 | public void testMetaDataSearch() { 54 | try { 55 | MetaDatas metadata = MetaDataApi.getMetaData("bigchaindb"); 56 | assertTrue(metadata.size() == 3); 57 | assertTrue(metadata.getMetaDatas().get(0).getId().equals("51ce82a14ca274d43e4992bbce41f6fdeb755f846e48e710a3bbb3b0cf8e4204")); 58 | } catch (IOException e) { 59 | e.printStackTrace(); 60 | } 61 | } 62 | 63 | /** 64 | * Test metadata search with limit. 65 | */ 66 | @Test 67 | public void testMetaDataSearchWithLimit() { 68 | try { 69 | MetaDatas metadata = MetaDataApi.getMetaDataWithLimit("bigchaindb", "2"); 70 | assertTrue(metadata.size() == 2); 71 | } catch (IOException e) { 72 | e.printStackTrace(); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/api/OutputsApiTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import static org.junit.Assert.assertTrue; 9 | 10 | import java.io.IOException; 11 | import java.security.spec.InvalidKeySpecException; 12 | import java.util.Iterator; 13 | 14 | import com.bigchaindb.AbstractTest; 15 | import com.bigchaindb.api.AssetsApi; 16 | import com.bigchaindb.api.OutputsApi; 17 | import com.bigchaindb.builders.BigchainDbConfigBuilder; 18 | import com.bigchaindb.model.Account; 19 | import com.bigchaindb.model.Output; 20 | import com.bigchaindb.model.Outputs; 21 | import com.bigchaindb.util.DriverUtils; 22 | import com.bigchaindb.util.JsonUtils; 23 | import com.bigchaindb.util.KeyPairUtils; 24 | 25 | import org.junit.BeforeClass; 26 | import org.junit.Test; 27 | 28 | import net.i2p.crypto.eddsa.EdDSAPublicKey; 29 | 30 | 31 | /** 32 | * The Class OutputsApiTest. 33 | */ 34 | public class OutputsApiTest extends AbstractApiTest { 35 | 36 | public static String PUBKEY = "1AAAbbb...ccc"; 37 | 38 | public static String V1_OUTPUTS_JSON = "[\n" + 39 | " {\n" + 40 | " \"output_index\": 0,\n" + 41 | " \"transaction_id\": \"2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e\"\n" + 42 | " },\n" + 43 | " {\n" + 44 | " \"output_index\": 1,\n" + 45 | " \"transaction_id\": \"2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e\"\n" + 46 | " }\n" + 47 | "]"; 48 | 49 | public static String V1_OUTPUTS_SPENT_JSON = "[\n" + 50 | " {\n" + 51 | " \"output_index\": 0,\n" + 52 | " \"transaction_id\": \"2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e\"\n" + 53 | " }\n" + 54 | "]"; 55 | 56 | public static String V1_OUTPUTS_UNSPENT_JSON = "[\n" + 57 | " {\n" + 58 | " \"output_index\": 1,\n" + 59 | " \"transaction_id\": \"2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e\"\n" + 60 | " }\n" + 61 | "]"; 62 | 63 | /** 64 | * Test get outputs. 65 | */ 66 | @Test 67 | public void testGetOutputs() { 68 | try { 69 | Outputs outputs = OutputsApi.getOutputs(PUBKEY); 70 | assertTrue(outputs.getOutput().size() == 2); 71 | } catch (IOException e) { 72 | e.printStackTrace(); 73 | } 74 | } 75 | 76 | /** 77 | * Test get spent outputs. 78 | */ 79 | @Test 80 | public void testGetSpentOutputs() { 81 | try { 82 | Outputs outputs = OutputsApi.getSpentOutputs(PUBKEY); 83 | assertTrue(outputs.getOutput().size() == 1); 84 | assertTrue(outputs.getOutput().get(0).getOutputIndex().equals(0)); 85 | assertTrue(outputs.getOutput().get(0).getTransactionId().equals("2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e")); 86 | } catch (IOException e) { 87 | e.printStackTrace(); 88 | } 89 | } 90 | 91 | /** 92 | * Test get unspent outputs. 93 | */ 94 | @Test 95 | public void testGetUnspentOutputs() { 96 | try { 97 | Outputs outputs = OutputsApi.getUnspentOutputs(PUBKEY); 98 | assertTrue(outputs.getOutput().size() == 1); 99 | assertTrue(outputs.getOutput().get(0).getOutputIndex().equals(1)); 100 | assertTrue(outputs.getOutput().get(0).getTransactionId().equals("2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e")); 101 | } catch (IOException e) { 102 | e.printStackTrace(); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/api/TransactionTransferApiTest.java: -------------------------------------------------------------------------------- 1 | package com.bigchaindb.api; 2 | 3 | import com.bigchaindb.builders.BigchainDbTransactionBuilder; 4 | import com.bigchaindb.constants.Operations; 5 | import com.bigchaindb.json.strategy.MetaDataDeserializer; 6 | import com.bigchaindb.json.strategy.MetaDataSerializer; 7 | import com.bigchaindb.json.strategy.TransactionDeserializer; 8 | import com.bigchaindb.json.strategy.TransactionsDeserializer; 9 | import com.bigchaindb.model.*; 10 | import com.bigchaindb.util.JsonUtils; 11 | import net.i2p.crypto.eddsa.EdDSAPrivateKey; 12 | import net.i2p.crypto.eddsa.EdDSAPublicKey; 13 | import okhttp3.Response; 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | import java.io.IOException; 18 | import java.math.BigDecimal; 19 | import java.security.KeyPair; 20 | import java.security.spec.InvalidKeySpecException; 21 | import java.util.ArrayList; 22 | import java.util.Date; 23 | import java.util.Map; 24 | import java.util.TreeMap; 25 | 26 | import static org.junit.Assert.assertEquals; 27 | import static org.junit.Assert.assertNotNull; 28 | import static org.junit.Assert.assertTrue; 29 | 30 | 31 | 32 | /** 33 | * The Class TransactionTransferApiTest. 34 | */ 35 | public class TransactionTransferApiTest extends AbstractApiTest { 36 | private static final String publicKey = "302a300506032b657003210033c43dc2180936a2a9138a05f06c892d2fb1cfda4562cbc35373bf13cd8ed373"; 37 | private static final String privateKey = "302e020100300506032b6570042204206f6b0cd095f1e83fc5f08bffb79c7c8a30e77a3ab65f4bc659026b76394fcea8"; 38 | 39 | /** 40 | * Test build transaction using builder. 41 | * 42 | * @throws InvalidKeySpecException 43 | */ 44 | @Test 45 | public void testBuildTransferTransaction() { 46 | try { 47 | Map assetData = new TreeMap() {{ 48 | put("msg", "Hello BigchainDB!"); 49 | }}; 50 | MetaData metaData = new MetaData(); 51 | 52 | Transaction transaction = BigchainDbTransactionBuilder 53 | .init() 54 | .addAssets(assetData, TreeMap.class) 55 | .operation(Operations.TRANSFER) 56 | .addMetaData(metaData) 57 | .buildAndSignOnly( 58 | (EdDSAPublicKey) Account.publicKeyFromHex(publicKey), 59 | (EdDSAPrivateKey) Account.privateKeyFromHex(privateKey)); 60 | 61 | assertTrue(transaction.getVersion().equals("2.0")); 62 | assertTrue(transaction.getSigned()); 63 | assertEquals(transaction.getOperation(), "TRANSFER"); 64 | } catch (Exception e) { 65 | e.printStackTrace(); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/api/ValidatorsApiTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.api; 7 | 8 | import org.junit.Test; 9 | 10 | import com.bigchaindb.api.ValidatorsApi; 11 | import com.bigchaindb.model.Validators; 12 | 13 | import java.io.IOException; 14 | 15 | import static org.junit.Assert.assertTrue; 16 | 17 | 18 | /** 19 | * The Class ValidatorsApiTest. 20 | */ 21 | public class ValidatorsApiTest extends AbstractApiTest { 22 | 23 | public static String V1_VALIDATORS_JSON = "[\n" + 24 | " {\n" + 25 | " \"pub_key\": {\n" + 26 | " \"data\":\"4E2685D9016126864733225BE00F005515200727FBAB1312FC78C8B76831255A\",\n" + 27 | " \"type\":\"ed25519\"\n" + 28 | " },\n" + 29 | " \"power\": 10\n" + 30 | " },\n" + 31 | " {\n" + 32 | " \"pub_key\": {\n" + 33 | " \"data\":\"608D839D7100466D6BA6BE79C320F8B81DE93CFAA58CF9768CF921C6371F2553\",\n" + 34 | " \"type\":\"ed25519\"\n" + 35 | " },\n" + 36 | " \"power\": 5\n" + 37 | " }\n" + 38 | "]"; 39 | 40 | /** 41 | * Test get validators. 42 | */ 43 | @Test 44 | public void testGetValidators() { 45 | try { 46 | Validators validators = ValidatorsApi.getValidators(); 47 | assertTrue(validators.getValidators().size() == 2); 48 | assertTrue(validators.getValidators().get(0).getPower() == 10); 49 | assertTrue(validators.getValidators().get(0).getPubKey().getData().equals("4E2685D9016126864733225BE00F005515200727FBAB1312FC78C8B76831255A")); 50 | assertTrue(validators.getValidators().get(0).getPubKey().getType().equals("ed25519")); 51 | } catch (IOException e) { 52 | // TODO Auto-generated catch block 53 | e.printStackTrace(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/builders/BigchainDBConnectionManagerTest.java: -------------------------------------------------------------------------------- 1 | package com.bigchaindb.builders; 2 | 3 | import java.security.KeyPair; 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.TreeMap; 9 | import java.util.concurrent.TimeoutException; 10 | 11 | import org.junit.After; 12 | import org.junit.Assert; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | 16 | import com.bigchaindb.constants.Operations; 17 | import com.bigchaindb.model.BigChainDBGlobals; 18 | import com.bigchaindb.model.Connection; 19 | import com.bigchaindb.model.MetaData; 20 | import com.bigchaindb.model.Transaction; 21 | 22 | import net.i2p.crypto.eddsa.EdDSAPrivateKey; 23 | import net.i2p.crypto.eddsa.EdDSAPublicKey; 24 | import net.jadler.JadlerMocker; 25 | import net.jadler.stubbing.server.jetty.JettyStubHttpServer; 26 | 27 | public class BigchainDBConnectionManagerTest { 28 | 29 | 30 | 31 | private JadlerMocker bdbNode1, bdbNode2, bdbNode3; 32 | private int bdbNode1Port, bdbNode2Port, bdbNode3Port; 33 | Map conn1Config = new HashMap(), 34 | conn2Config = new HashMap(), 35 | conn3Config = new HashMap(); 36 | private final String LOCALHOST = "http://localhost:"; 37 | 38 | List connections = new ArrayList(); 39 | Map headers = new HashMap(); 40 | 41 | @Before 42 | public void setUp() { 43 | //setup mock node 1 44 | bdbNode1 = new JadlerMocker(new JettyStubHttpServer()); 45 | bdbNode1.start(); 46 | bdbNode1Port = bdbNode1.getStubHttpServerPort(); 47 | System.out.println("port1 - " + bdbNode1Port); 48 | 49 | //setup mock node 2 50 | bdbNode2 = new JadlerMocker(new JettyStubHttpServer()); 51 | bdbNode2.start(); 52 | bdbNode2Port = bdbNode2.getStubHttpServerPort(); 53 | System.out.println("port2 - " + bdbNode2Port); 54 | 55 | //set up mock node 3 56 | bdbNode3 = new JadlerMocker(new JettyStubHttpServer()); 57 | bdbNode3.start(); 58 | bdbNode3Port = bdbNode3.getStubHttpServerPort(); 59 | System.out.println("port3 - " + bdbNode3Port); 60 | 61 | //define headers 62 | headers.put("app_id", ""); 63 | headers.put("app_key", ""); 64 | 65 | conn1Config.put("baseUrl", LOCALHOST.concat(Integer.toString(bdbNode1Port))); 66 | conn1Config.put("headers", headers); 67 | Connection conn1 = new Connection(conn1Config); 68 | 69 | conn2Config.put("baseUrl", LOCALHOST.concat(Integer.toString(bdbNode2Port))); 70 | conn2Config.put("headers", headers); 71 | Connection conn2 = new Connection(conn2Config); 72 | 73 | conn3Config.put("baseUrl", LOCALHOST.concat(Integer.toString(bdbNode3Port))); 74 | conn3Config.put("headers", headers); 75 | Connection conn3 = new Connection(conn3Config); 76 | 77 | connections.add(conn1); 78 | connections.add(conn2); 79 | connections.add(conn3); 80 | 81 | 82 | BigChainDBGlobals.setTimeout(10000); 83 | 84 | } 85 | 86 | @After 87 | public void tearDown() { 88 | if(bdbNode1.isStarted()) 89 | bdbNode1.close(); 90 | if(bdbNode2.isStarted()) 91 | bdbNode2.close(); 92 | if(bdbNode3.isStarted()) 93 | bdbNode3.close(); 94 | } 95 | 96 | @Test 97 | public void nodeIsReusedOnSuccessfulConnection() throws Exception { 98 | //check that node is up 99 | if(!bdbNode1.isStarted()) { 100 | bdbNode1.start(); 101 | }; 102 | 103 | bdbNode1 104 | .onRequest() 105 | .havingMethodEqualTo("GET") 106 | .havingPathEqualTo("/api/v1") 107 | .respond() 108 | .withStatus(200); 109 | 110 | BigchainDbConfigBuilder 111 | .addConnections(connections) 112 | .setup(); 113 | 114 | String actualBaseUrl = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 115 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode1Port)), actualBaseUrl); 116 | 117 | sendCreateTransaction(); 118 | 119 | String newBaseUrl = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 120 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode1Port)), newBaseUrl); 121 | 122 | } 123 | 124 | @Test 125 | public void secondNodeIsUsedIfFirstNodeGoesDown() throws Exception { 126 | //check that nodes are up 127 | if(!bdbNode1.isStarted()) { 128 | bdbNode1.start(); 129 | }; 130 | 131 | if(!bdbNode2.isStarted()) { 132 | bdbNode2.start(); 133 | }; 134 | 135 | 136 | //start listening on node 1 137 | bdbNode1 138 | .onRequest() 139 | .havingMethodEqualTo("GET") 140 | .havingPathEqualTo("/api/v1") 141 | .respond() 142 | .withStatus(200); 143 | 144 | //start listening on node 2 145 | bdbNode2 146 | .onRequest() 147 | .havingMethodEqualTo("GET") 148 | .havingPathEqualTo("/api/v1") 149 | .respond() 150 | .withStatus(200); 151 | 152 | BigchainDbConfigBuilder 153 | .addConnections(connections) 154 | .setup(); 155 | 156 | //check if driver is connected to first node 157 | String actualBaseUrl = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 158 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode1Port)), actualBaseUrl); 159 | 160 | //shut down node 1 161 | bdbNode1.close(); 162 | 163 | //now transaction should be send by node 2 164 | sendCreateTransaction(); 165 | 166 | //verify driver is connected to node 2 167 | String newBaseUrl = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 168 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode2Port)), newBaseUrl); 169 | 170 | } 171 | 172 | @Test 173 | public void verifyMetaValuesForNodesAreUpdatedCorrectly() throws Exception { 174 | //check that nodes are up 175 | if(!bdbNode1.isStarted()) { 176 | bdbNode1.start(); 177 | }; 178 | 179 | if(!bdbNode2.isStarted()) { 180 | bdbNode2.start(); 181 | }; 182 | 183 | if(!bdbNode3.isStarted()) { 184 | bdbNode3.start(); 185 | }; 186 | 187 | //start listening on node 1 188 | bdbNode1 189 | .onRequest() 190 | .havingMethodEqualTo("GET") 191 | .havingPathEqualTo("/api/v1") 192 | .respond() 193 | .withStatus(200); 194 | 195 | //start listening on node 2 196 | bdbNode2 197 | .onRequest() 198 | .havingMethodEqualTo("GET") 199 | .havingPathEqualTo("/api/v1") 200 | .respond() 201 | .withStatus(200); 202 | 203 | //start listening on node 3 204 | bdbNode3 205 | .onRequest() 206 | .havingMethodEqualTo("GET") 207 | .havingPathEqualTo("/api/v1") 208 | .respond() 209 | .withStatus(200); 210 | 211 | BigchainDbConfigBuilder 212 | .addConnections(connections) 213 | .setup(); 214 | 215 | //verify meta values of nodes are initialized as 0 216 | for(Connection conn : BigChainDBGlobals.getConnections()) { 217 | Assert.assertTrue(conn.getTimeToRetryForConnection() == 0); 218 | Assert.assertTrue(conn.getRetryCount() == 0); 219 | } 220 | 221 | //check if driver is connected to first node 222 | String actualBaseUrl = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 223 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode1Port)), actualBaseUrl); 224 | 225 | //shut down node 1 226 | bdbNode1.close(); 227 | 228 | 229 | //now transaction should be send by node 2 230 | sendCreateTransaction(); 231 | 232 | String baseUrl1 = "", baseUrl2 = ""; 233 | //verify meta values of nodes are initialized as 0 234 | for(Connection conn : BigChainDBGlobals.getConnections()) { 235 | 236 | baseUrl1 = (String) conn.getConnection().get("baseUrl"); 237 | if(baseUrl1.equals(LOCALHOST.concat(Integer.toString(bdbNode1Port)))) { 238 | Assert.assertTrue(conn.getTimeToRetryForConnection() != 0); 239 | Assert.assertTrue((conn.getTimeToRetryForConnection() - System.currentTimeMillis()) <= BigChainDBGlobals.getTimeout()); 240 | Assert.assertTrue(conn.getRetryCount() == 1); 241 | } 242 | } 243 | 244 | //verify driver is connected to node 2 245 | String newBaseUrl = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 246 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode2Port)), newBaseUrl); 247 | 248 | //shut down node 2 249 | bdbNode2.close(); 250 | 251 | //now transaction should be send by node 3 252 | sendCreateTransaction(); 253 | 254 | long T1 = 0, T2 =0; 255 | //verify meta values of nodes 256 | for(Connection conn : BigChainDBGlobals.getConnections()) { 257 | 258 | baseUrl2 = (String) conn.getConnection().get("baseUrl"); 259 | if(baseUrl2.equals(LOCALHOST.concat(Integer.toString(bdbNode2Port)))) { 260 | T2 = conn.getTimeToRetryForConnection(); 261 | Assert.assertTrue(T2 != 0); 262 | Assert.assertTrue((T2 - System.currentTimeMillis()) <= BigChainDBGlobals.getTimeout()); 263 | Assert.assertTrue(conn.getRetryCount() == 1); 264 | } 265 | 266 | baseUrl1 = (String) conn.getConnection().get("baseUrl"); 267 | if(baseUrl1.equals(LOCALHOST.concat(Integer.toString(bdbNode1Port)))) { 268 | T1 = conn.getTimeToRetryForConnection(); 269 | Assert.assertTrue(T1 != 0); 270 | Assert.assertTrue(conn.getRetryCount() == 1); 271 | } 272 | 273 | } 274 | 275 | //verify that T1 < T2 276 | Assert.assertTrue(T1 < T2); 277 | } 278 | 279 | @Test(expected = TimeoutException.class) 280 | public void shouldThrowTimeoutException() throws Exception{ 281 | //check that nodes are up 282 | if(!bdbNode1.isStarted()) { 283 | bdbNode1.start(); 284 | }; 285 | 286 | if(!bdbNode2.isStarted()) { 287 | bdbNode2.start(); 288 | }; 289 | 290 | //start listening on node 1 291 | bdbNode1 292 | .onRequest() 293 | .havingMethodEqualTo("GET") 294 | .havingPathEqualTo("/api/v1") 295 | .respond() 296 | .withStatus(200); 297 | 298 | //start listening on node 2 299 | bdbNode2 300 | .onRequest() 301 | .havingMethodEqualTo("GET") 302 | .havingPathEqualTo("/api/v1") 303 | .respond() 304 | .withStatus(200); 305 | 306 | //start listening on node 3 307 | bdbNode3 308 | .onRequest() 309 | .havingMethodEqualTo("GET") 310 | .havingPathEqualTo("/api/v1") 311 | .respond() 312 | .withStatus(200); 313 | 314 | BigchainDbConfigBuilder 315 | .addConnections(connections) 316 | .setup(); 317 | 318 | //check if driver is connected to first node 319 | String url1 = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 320 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode1Port)), url1); 321 | 322 | //shut down node 1 323 | bdbNode1.close(); 324 | 325 | //now transaction should be send by node 2 326 | sendCreateTransaction(); 327 | 328 | //check if driver is connected to node 2 329 | String url2 = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 330 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode2Port)), url2); 331 | 332 | //shut down node 1 333 | bdbNode2.close(); 334 | 335 | //now transaction should be send by node 2 336 | sendCreateTransaction(); 337 | 338 | //check if driver is connected to node 3 339 | String url3 = (String) BigChainDBGlobals.getCurrentNode().getConnection().get("baseUrl"); 340 | Assert.assertEquals("Failed because of node", LOCALHOST.concat(Integer.toString(bdbNode3Port)), url3); 341 | 342 | //shut down node 1 343 | bdbNode3.close(); 344 | 345 | //now transaction should be send by node 2 346 | sendCreateTransaction(); 347 | } 348 | 349 | public String sendCreateTransaction() throws TimeoutException, Exception{ 350 | 351 | 352 | net.i2p.crypto.eddsa.KeyPairGenerator edDsaKpg = new net.i2p.crypto.eddsa.KeyPairGenerator(); 353 | KeyPair keys = edDsaKpg.generateKeyPair(); 354 | 355 | // create New asset 356 | Map assetData = new TreeMap() {{ 357 | put("name", "James Bond"); 358 | put("age", "doesn't matter"); 359 | put("purpose", "saving the world"); 360 | }}; 361 | System.out.println("(*) Assets Prepared.."); 362 | 363 | // create metadata 364 | MetaData metaData = new MetaData(); 365 | metaData.setMetaData("where is he now?", "Thailand"); 366 | System.out.println("(*) Metadata Prepared.."); 367 | //build and send CREATE transaction 368 | Transaction transaction = null; 369 | 370 | transaction = BigchainDbTransactionBuilder 371 | .init() 372 | .addAssets(assetData, TreeMap.class) 373 | .addMetaData(metaData) 374 | .operation(Operations.CREATE) 375 | .buildAndSign((EdDSAPublicKey) keys.getPublic(), (EdDSAPrivateKey) keys.getPrivate()) 376 | .sendTransaction(); 377 | 378 | System.out.println("(*) CREATE Transaction sent.. - " + transaction.getId()); 379 | return transaction.getId(); 380 | } 381 | 382 | } 383 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/keys/PrivateKeyTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.keys; 7 | 8 | import static org.hamcrest.CoreMatchers.equalTo; 9 | import static org.hamcrest.CoreMatchers.is; 10 | import static org.junit.Assert.assertThat; 11 | import java.security.spec.PKCS8EncodedKeySpec; 12 | import org.junit.Test; 13 | import net.i2p.crypto.eddsa.EdDSAPrivateKey; 14 | import net.i2p.crypto.eddsa.Utils; 15 | import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec; 16 | 17 | public class PrivateKeyTest { 18 | 19 | /** 20 | * The example private key 21 | * MC4CAQAwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC from 22 | * https://tools.ietf.org/html/draft-ietf-curdle-pkix-04#section-10.3 23 | */ 24 | static final byte[] TEST_PRIVKEY = Utils.hexToBytes( 25 | "302e020100300506032b657004220420d4ee72dbf913584ad5b6d8f1f769f8ad3afe7c28cbf1d4fbe097a88f44755842"); 26 | 27 | static final byte[] TEST_PRIVKEY_NULL_PARAMS = Utils.hexToBytes( 28 | "3030020100300706032b6570050004220420d4ee72dbf913584ad5b6d8f1f769f8ad3afe7c28cbf1d4fbe097a88f44755842"); 29 | static final byte[] TEST_PRIVKEY_OLD = Utils.hexToBytes( 30 | "302f020100300806032b65640a01010420d4ee72dbf913584ad5b6d8f1f769f8ad3afe7c28cbf1d4fbe097a88f44755842"); 31 | 32 | @Test 33 | public void testDecodeAndEncode() throws Exception { 34 | // Decode 35 | PKCS8EncodedKeySpec encoded = new PKCS8EncodedKeySpec(TEST_PRIVKEY); 36 | EdDSAPrivateKey keyIn = new EdDSAPrivateKey(encoded); 37 | 38 | // Encode 39 | EdDSAPrivateKeySpec decoded = new EdDSAPrivateKeySpec(keyIn.getSeed(), keyIn.getH(), keyIn.geta(), keyIn.getA(), 40 | keyIn.getParams()); 41 | EdDSAPrivateKey keyOut = new EdDSAPrivateKey(decoded); 42 | 43 | // Check 44 | assertThat(keyOut.getEncoded(), is(equalTo(TEST_PRIVKEY))); 45 | } 46 | 47 | @Test 48 | public void testDecodeWithNullAndEncode() throws Exception { 49 | // Decode 50 | PKCS8EncodedKeySpec encoded = new PKCS8EncodedKeySpec(TEST_PRIVKEY_NULL_PARAMS); 51 | EdDSAPrivateKey keyIn = new EdDSAPrivateKey(encoded); 52 | 53 | // Encode 54 | EdDSAPrivateKeySpec decoded = new EdDSAPrivateKeySpec(keyIn.getSeed(), keyIn.getH(), keyIn.geta(), keyIn.getA(), 55 | keyIn.getParams()); 56 | EdDSAPrivateKey keyOut = new EdDSAPrivateKey(decoded); 57 | 58 | // Check 59 | assertThat(keyOut.getEncoded(), is(equalTo(TEST_PRIVKEY))); 60 | } 61 | 62 | @Test 63 | public void testReEncodeOldEncoding() throws Exception { 64 | // Decode 65 | PKCS8EncodedKeySpec encoded = new PKCS8EncodedKeySpec(TEST_PRIVKEY_OLD); 66 | EdDSAPrivateKey keyIn = new EdDSAPrivateKey(encoded); 67 | 68 | // Encode 69 | EdDSAPrivateKeySpec decoded = new EdDSAPrivateKeySpec(keyIn.getSeed(), keyIn.getH(), keyIn.geta(), keyIn.getA(), 70 | keyIn.getParams()); 71 | EdDSAPrivateKey keyOut = new EdDSAPrivateKey(decoded); 72 | 73 | // Check 74 | assertThat(keyOut.getEncoded(), is(equalTo(TEST_PRIVKEY))); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/keys/PublicKeyTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.keys; 7 | 8 | import static org.hamcrest.CoreMatchers.equalTo; 9 | import static org.hamcrest.CoreMatchers.is; 10 | import static org.junit.Assert.assertThat; 11 | 12 | import java.security.spec.X509EncodedKeySpec; 13 | 14 | import org.junit.Test; 15 | 16 | import net.i2p.crypto.eddsa.EdDSAPublicKey; 17 | import net.i2p.crypto.eddsa.Utils; 18 | import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec; 19 | 20 | public class PublicKeyTest { 21 | /** 22 | * The example public key MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE= 23 | * from https://tools.ietf.org/html/draft-ietf-curdle-pkix-04#section-10.1 24 | */ 25 | static final byte[] TEST_PUBKEY = Utils.hexToBytes("302a300506032b657003210019bf44096984cdfe8541bac167dc3b96c85086aa30b6b6cb0c5c38ad703166e1"); 26 | 27 | static final byte[] TEST_PUBKEY_NULL_PARAMS = Utils.hexToBytes("302c300706032b6570050003210019bf44096984cdfe8541bac167dc3b96c85086aa30b6b6cb0c5c38ad703166e1"); 28 | static final byte[] TEST_PUBKEY_OLD = Utils.hexToBytes("302d300806032b65640a010103210019bf44096984cdfe8541bac167dc3b96c85086aa30b6b6cb0c5c38ad703166e1"); 29 | 30 | @Test 31 | public void testDecodeAndEncode() throws Exception { 32 | // Decode 33 | X509EncodedKeySpec encoded = new X509EncodedKeySpec(TEST_PUBKEY); 34 | EdDSAPublicKey keyIn = new EdDSAPublicKey(encoded); 35 | 36 | // Encode 37 | EdDSAPublicKeySpec decoded = new EdDSAPublicKeySpec( 38 | keyIn.getA(), 39 | keyIn.getParams()); 40 | EdDSAPublicKey keyOut = new EdDSAPublicKey(decoded); 41 | 42 | // Check 43 | assertThat(keyOut.getEncoded(), is(equalTo(TEST_PUBKEY))); 44 | } 45 | 46 | @Test 47 | public void testDecodeWithNullAndEncode() throws Exception { 48 | // Decode 49 | X509EncodedKeySpec encoded = new X509EncodedKeySpec(TEST_PUBKEY_NULL_PARAMS); 50 | EdDSAPublicKey keyIn = new EdDSAPublicKey(encoded); 51 | 52 | // Encode 53 | EdDSAPublicKeySpec decoded = new EdDSAPublicKeySpec( 54 | keyIn.getA(), 55 | keyIn.getParams()); 56 | EdDSAPublicKey keyOut = new EdDSAPublicKey(decoded); 57 | 58 | // Check 59 | assertThat(keyOut.getEncoded(), is(equalTo(TEST_PUBKEY))); 60 | } 61 | 62 | @Test 63 | public void testReEncodeOldEncoding() throws Exception { 64 | // Decode 65 | X509EncodedKeySpec encoded = new X509EncodedKeySpec(TEST_PUBKEY_OLD); 66 | EdDSAPublicKey keyIn = new EdDSAPublicKey(encoded); 67 | 68 | // Encode 69 | EdDSAPublicKeySpec decoded = new EdDSAPublicKeySpec( 70 | keyIn.getA(), 71 | keyIn.getParams()); 72 | EdDSAPublicKey keyOut = new EdDSAPublicKey(decoded); 73 | 74 | // Check 75 | assertThat(keyOut.getEncoded(), is(equalTo(TEST_PUBKEY))); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/util/KeyPairUtilsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.util; 7 | 8 | 9 | import org.junit.Assert; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | import com.bigchaindb.util.KeyPairUtils; 14 | 15 | import java.security.KeyPair; 16 | 17 | public class KeyPairUtilsTest { 18 | 19 | private KeyPair generatedKeyPair; 20 | 21 | /** 22 | * Inits the. 23 | */ 24 | @Before 25 | public void init() { 26 | generatedKeyPair = KeyPairUtils.generateNewKeyPair(); 27 | } 28 | 29 | @Test 30 | public void testBytesEncoding() { 31 | byte[] encodedKey = KeyPairUtils.encodePrivateKey(generatedKeyPair); 32 | KeyPair decodedKeyPair = KeyPairUtils.decodeKeyPair(encodedKey); 33 | Assert.assertArrayEquals(generatedKeyPair.getPrivate().getEncoded(), 34 | decodedKeyPair.getPrivate().getEncoded()); 35 | } 36 | 37 | @Test 38 | public void testBase64Encoding() { 39 | String encodedKey = KeyPairUtils.encodePrivateKeyBase64(generatedKeyPair); 40 | KeyPair decodedKeyPair = KeyPairUtils.decodeKeyPair(encodedKey); 41 | Assert.assertArrayEquals(generatedKeyPair.getPrivate().getEncoded(), 42 | decodedKeyPair.getPrivate().getEncoded()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/util/ScannerUtilsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.util; 7 | 8 | import org.junit.Test; 9 | 10 | import com.bigchaindb.util.ScannerUtil; 11 | 12 | import java.io.ByteArrayInputStream; 13 | import java.io.InputStream; 14 | 15 | public class ScannerUtilsTest { 16 | 17 | @Test 18 | public void testMonitorExit() { 19 | InputStream fakeIn = new ByteArrayInputStream("exit".getBytes()); 20 | System.setIn(fakeIn); 21 | ScannerUtil.monitorExit(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/ws/ValidTransactionMessageHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.ws; 7 | 8 | import com.bigchaindb.model.ValidTransaction; 9 | import com.bigchaindb.util.JsonUtils; 10 | import com.bigchaindb.ws.MessageHandler; 11 | 12 | public class ValidTransactionMessageHandler implements MessageHandler { 13 | @Override 14 | public void handleMessage(String message) { 15 | ValidTransaction validTransaction = JsonUtils.fromJson(message, ValidTransaction.class); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/bigchaindb/ws/WsMonitorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright BigchainDB GmbH and BigchainDB contributors 3 | * SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) 4 | * Code is Apache-2.0 and docs are CC-BY-4.0 5 | */ 6 | package com.bigchaindb.ws; 7 | 8 | import static net.jadler.Jadler.port; 9 | 10 | import java.util.ArrayList; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.concurrent.TimeoutException; 15 | 16 | import com.bigchaindb.builders.BigchainDbConfigBuilder; 17 | import com.bigchaindb.model.Connection; 18 | 19 | public class WsMonitorTest { 20 | 21 | public static void main(String[] args) { 22 | 23 | Map connConfig = new HashMap(); 24 | List connections = new ArrayList(); 25 | Map headers = new HashMap(); 26 | 27 | //define headers 28 | headers.put("app_id", "2bbaf3ff"); 29 | headers.put("app_key", "c929b708177dcc8b9d58180082029b8d"); 30 | 31 | connConfig.put("baseUrl", "http://localhost:" + port()); 32 | connConfig.put("headers", headers); 33 | Connection conn1 = new Connection(connConfig); 34 | connections.add(conn1); 35 | BigchainDbConfigBuilder 36 | .addConnections(connections) 37 | .webSocketMonitor(new MessageHandler() { 38 | @Override 39 | public void handleMessage(String message) { 40 | } 41 | }) 42 | .setup(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2014. 3 | # 4 | # Need to update this 5 | # 6 | 7 | 8 | # Set root logger level 9 | log4j.rootLogger=DEBUG, rootAppender 10 | log4j.appender.rootAppender=org.apache.log4j.ConsoleAppender 11 | log4j.appender.rootAppender.layout=org.apache.log4j.PatternLayout 12 | log4j.appender.rootAppender.layout.ConversionPattern=%d{yyyyMMdd-HH:mm:ss} %-4r [%t] %-5p %c %x - %m%n 13 | 14 | log4j.appender.fileAppender=org.apache.log4j.FileAppender 15 | log4j.appender.fileAppender.append=true 16 | log4j.appender.fileAppender.file=SideBdbServer.log 17 | log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout 18 | log4j.appender.fileAppender.layout.ConversionPattern=%d{yyyyMMdd-HH:mm:ss} %-4r [%t] %-5p %c %x - %m%n 19 | -------------------------------------------------------------------------------- /src/test/resources/test.properties: -------------------------------------------------------------------------------- 1 | test.api.url=http://localhost:9984 2 | test.app.id=2bbaf3ff 3 | test.app.key=c929b708177dcc8b9d58180082029b8d 4 | test.status.retries=300 --------------------------------------------------------------------------------