Giter Club home page Giter Club logo

ckb-sdk-java's Introduction

CKB SDK Java

License Github Actions CI Maven Central Telegram Group

Java SDK for Nervos CKB.

Prerequisites

  • Java 8
  • Gradle 5.0 or later

Installation

Maven

<dependency>
  <groupId>org.nervos.ckb</groupId>
  <artifactId>ckb</artifactId>
  <version>{version}</version>
</dependency>

Gradle

implementation 'org.nervos.ckb:ckb:{version}'

Build

Run gradle build in project root directory.

Quick start

Here we will give some most frequently used operations, to bring you enlightenment about how to use ckb-sdk-java to operate your asset in CKB chain.

Setup

ckb-sdk-java provides a convenient client to help you easily interact with CKB node.

// Set up client.
CkbRpcApi ckbAPi = new Api("http://127.0.0.1:8114");

You can leverage this client to call any RPC APIs provided by CKB in Java code.

byte[] blockHash = Numeric.hexStringToByteArray("0x77fdd22f6ae8a717de9ae2b128834e9b2a1424378b5fc95606ba017aab5fed75");
Block block = ckbApi.getBlock(blockHash);

For more details about CKB RPC APIs, please refer to CKB RPC doc.

Build transaction by manual

ckb-sdk-java encapsulates the common logic into a user-friendly transaction builder. It could greatly free you from getting into script details and from tedious manual work of building transaction including adding celldeps, transaction fee calculation, change output set and so on.

Here is an example to build a CKB transfer transaction with the help of transaction builder and ckb node.

String sender = "ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq2qf8keemy2p5uu0g0gn8cd4ju23s5269qk8rg4r";
String receiver = "ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqg958atl2zdh8jn3ch8lc72nt0cf864ecqdxm9zf";
Iterator<TransactionInput> iterator = new InputIterator(sender);
TransactionBuilderConfiguration configuration = new TransactionBuilderConfiguration(Network.TESTNET);
configuration.setFeeRate(1000);
TransactionWithScriptGroups txWithGroups = new CkbTransactionBuilder(configuration, iterator)
    .addOutput(receiver, 50100000000L)
    .setChangeOutput(sender)
    .build();

For more use cases of building transaction with ckb node, please refer to these examples.

Build transaction with Mercury

Mercury is an application for better interaction with CKB chain, providing many useful RPC APIs for development like querying transactions or getting UDT asset information. You need to deploy your own mercury server and sync data with the latest network before using it.

Mercury is another way to build transaction. With the help of Mercury, you can build a transaction by simply calling a JSON-RPC API. Here we show how to build a CKB transfer transaction with mercury.

String sender = "ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq0yvcdtsu5wcr2jldtl72fhkruf0w5vymsp6rk9r";
String receiver = "ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqvglkprurm00l7hrs3rfqmmzyy3ll7djdsujdm6z";

long ckbAmount = AmountUtils.ckbToShannon(100);   // Convert CKB to Shannon (1 CKB = 10^8 Shannon)
SimpleTransferPayloadBuilder builder = new SimpleTransferPayloadBuilder();
builder.addFrom(sender);
builder.addTo(receiver, ckbAmount);
builder.assetInfo(AssetInfo.newCkbAsset());

// Get an unsigned raw transaction with the help of Mercury
MercuryApi mercuryApi = new DefaultMercuryApi("http://127.0.0.1:8116", false);
TransactionWithScriptGroups txWithScriptGroups = mercuryApi.buildSimpleTransferTransaction(builder.build());

For more use cases of mercury, please refer to these test cases and Mercury JSON-RPC documentation.

Sign and send transaction

To send transaction you build to CKB network, you need to

  1. sign transaction with your private key.
  2. send signed transaction to CKB node, and wait it to be confirmed.

Before signing and sending transaction, you need to prepare a raw transaction represented by an instance of class TransactionWithScriptGroups. You can get it by Mercury or by manual

// 0. Set your private key
String privateKey = "0x6c9ed03816e31...";
// 1. Sign transaction with your private key
TransactionSigner.getInstance(Network.TESTNET).signTransaction(txWithScriptGroups, privateKey);
// 2. Send transaction to CKB node
byte[] txHash = ckbApi.sendTransaction(txWithScriptGroups.txView);
System.out.println(Numeric.toHexString(txHash));

Generate a new address

In CKB world, a lock script can be represented as an address. secp256k1_blake160 is the most common used address and here we show how to generate it.

// Generate a new address randomly
ECKeyPair keyPair = Keys.createEcKeyPair();
Script script = Script.generateSecp256K1Blake160SignhashAllScript(keyPair));
Address address = new Address(script, Network.TESTNET);
System.out.println(address.encode());

For more details please about CKB address refer to CKB rfc 0021.

Convert public key to address

Convert elliptic curve public key to an address (secp256k1_blake160)

// The public key sent is an elliptic curve public key of compressed format - a 65-length hex (not include hex prefix 0x).
byte[] publicKey = Numeric.hexStringToByteArray("0x24a501efd328e062c8675f2365970728c859c592beeefd6be8ead3d901330bc01");
Script script = Script.generateSecp256K1Blake160SignhashAllScript(publicKey);
Address address = new Address(script, Network.TESTNET);
System.out.println(address.encode());

Parse address

Short address and full bech32 address are deprecated. The standard address encoded way is bech32m. You can parse address from an encoded string address and then get its network, script and encoded string of other format.

Address address = Address.decode("ckt1qyqxgp7za7dajm5wzjkye52asc8fxvvqy9eqlhp82g");
Script script = address.getScript();
Network network = address.getNetwork();
System.out.println(address.encode());

Contributing

See CONTRIBUTING.md.

License

The SDK is available as open source under the terms of the MIT License.

Changelog

See CHANGELOG for more information.

ckb-sdk-java's People

Contributors

ashchan avatar baojuncz avatar blckngm avatar classicalliu avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar doitian avatar duanyytop avatar github-actions[bot] avatar hanssen0 avatar jimzk avatar quake avatar rev-chaos avatar shaojunda avatar zhengjianhui avatar

Stargazers

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

Watchers

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

ckb-sdk-java's Issues

get_transaction

request the get_transaction,that get the transaction info without address.
so how can i know which address receive the ckb coin

README examples are deprecated

https://github.com/nervosnetwork/ckb-sdk-java/tree/master#build-transaction-by-manual

This is the latest working example

var sender = "ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq2qf8keemy2p5uu0g0gn8cd4ju23s5269qk8rg4r";
var receiver = "ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqg958atl2zdh8jn3ch8lc72nt0cf864ecqdxm9zf";
var iterator = new InputIterator(sender);
var configuration = new TransactionBuilderConfiguration(Network.TESTNET);
configuration.setFeeRate(1000);
TransactionWithScriptGroups txWithGroups = new CkbTransactionBuilder(configuration, iterator)
    .addOutput(receiver, 50100000000L)
    .setChangeOutput(sender)
    .build();

send_transaction has an error

{"cellDeps":[{"depType":"dep_group","outPoint":{"index":"0x0","txHash":"0xbd864a269201d7052d4eb3f753f49f7c68b8edc386afc8bb6ef3e15a05facca2"}}],"headerDeps":[],"inputs":[{"previousOutput":{"index":"0x0","txHash":"0x19e827fb8bf5f3b1a056823f9e64df78fdfe3d10f99ecc0de560c215bfd07d6d"},"since":"0x0"}],"outputs":[{"capacity":"0x174876e800","lock":{"args":"0xfebc0705dc7f9a1e55874c4b8196051717a3b262","codeHash":"0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8","hashType":"type"}},{"capacity":"0x5d21cc5dc0","lock":{"args":"0x4d11235ddc00871218b98ed23cbc433f252e88b8","codeHash":"0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8","hashType":"type"}}],"outputsData":["0x","0x"],"version":"0x0","witnesses":["0x55000000100000005500000055000000410000002d53dc8f4b68bcf6d323bfa969f5773b52e8c40af2b5fcaad393b2a7ab6ecd8d47f891b1d6aa0d76d7f85c67d65dc833254c3167932b1fb6f981ecef3bed88f400"]}

java.io.IOException: RpcService method send_transaction error {"code":-3,"message":"Script(ValidationFailure(-31))"}

转账失败TransactionFailedToVerify报错

RpcService method send_transaction error {"code":-302,"message":"TransactionFailedToVerify: Verification failed Script(TransactionScriptError { source: Inputs[0].Lock, cause: ValidationFailure: see the error code -31 in the page https://nervosnetwork.github.io/ckb-script-error-codes/by-type-hash/9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8.html#-31 })"}

各位大佬,不同的cell 有不同的lock,导致单一签名失败,有没有example解决这个问题

Update send transaction (capacity) example to support inputs from multiple lock scripts

Currently the SDK collects inputs from a single address (and sign with the private key for that address). This task is to:

  • Provide multiple private keys when constructing a tx
  • Derive lock scripts for those private keys
  • Sign witnesses with these keys

To sign inputs with multiple private keys

  • Update Transaction.sign and add signInput method
    • The new signInput(index, private key) method signs the input at the specified index, with the provided private key
    • When signing a single input, only the witness for that input should be signed and updated
    • The current sign method can be updated to iterate over all inputs and sign each by using signInput
  • [ ] Provide a default implementation for collect inputs for multiple (private keys ->) lock scripts/addresses

wrong expected_type_hash

v 0.19.0 release used wrong expected_type_hash.
While ruby-sdk use
expected_type_hash = "0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88"
but java computed "0xf6d0736d63b5ab0629ef574344bb59e4becb7874a5a170f8bb503509b3b2baf2"

and send_tx got
java.io.IOException: InvalidTx(ScriptFailure(InvalidCodeHash))

improve gradle build script

TODO

  • git pre-commit hooks with gradle googleJavaFormat
  • git pre-push hooks with gradle clean build -x test

run error of ckb-sdk-java at centos 7

Describe the bug
i did the ./gradlew clean build and ./gradlew run. but i got the error like this

(#) ./gradlew run

Task :run FAILED
Error: Could not find or load main class org.nervos.ckb.example.APIClient
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':run'.
Process 'command '/root/test/jdk1.8.0_131/bin/java'' finished with non-zero exit value 1
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Get more help at https://help.gradle.org
BUILD FAILED in 0s
1 actionable task: 1 executed

Header model missing some fields

{
            "compact_target": "0x1e083126",
            "dao": "0xb5a3e047474401001bc476b9ee573000c0c387962a38000000febffacf030000",
            "epoch": "0x7080018000001",
            "hash": "0xa5f5c85987a15de25661e5a214f2c1449cd803f071acc7999820f25246471f40",
            "nonce": "0x0",
            "number": "0x400",
            "parent_hash": "0xae003585fa15309b30b31aed3dcf385e9472c3c3e93746a6c4540629a6a1ed2d",
            "proposals_hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
            "timestamp": "0x5cd2b117",
            "transactions_root": "0xc47d5b78b3c4c4c853e2a32810818940d0ee403423bea9ec7b8e566d9595206c",
            "uncles_hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
            "version": "0x0"
}

Failed to post request on RPC : {Caused by: java.io.EOFException: \n not found:…}

at org.nervos.ckb.service.RpcService.post(RpcService.java:41)
at org.nervos.ckb.service.Api.getBlockchainInfo(Api.java:113)
at org.nervos.ckb.RpcExample.getBlockchainInfo(RpcExample.java:49)
at org.nervos.ckb.RpcExample.run(RpcExample.java:24)
at org.nervos.ckb.RpcExample.main(RpcExample.java:30)

Caused by: java.io.EOFException: \n not found: limit=210 content=000000cece000000180000002c0000005900000068000000bd00000010000000…

Blake160 parsed from some address are not correct

SDK version: https://github.com/nervosnetwork/ckb-sdk-java/releases/tag/v0.33.0
( PS. also verified on latest develop branch, commit id: 02a425a, but same result)

verification code:

@Test
  public void testBlake160FromAddressTestnet() {
    String blake160 = AddressUtils.parse("ckt1qyq2742g7yajdcahqsyn63spqrlspyy8g5pq7xg9tu");
    Assertions.assertEquals(blake160, "af5548f13b26e3b704093d460100ff0090874502");
  }

case1: the args parsed from ckt1qyq2742g7yajdcahqsyn63spqrlspyy8g5pq7xg9tu should be af5548f13b26e3b704093d460100ff0090874502, but returned af5548f13b26e3b704093d46ff0090874502, which lack of 0100;

case2: the args parsed from ckt1qyqrmp8wgqgq3j32lv55hequf54zgv0t679q4cj25k should be 3d84ee401008ca2afb294be41c4d2a2431ebd78a, but returned 3d84ee48ca2afb294be41c4d2a2431ebd78a, which also lack of 0100;

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.