HyperLedger Indy的使用(Java+Python)

Write a DID and Query Its Verkey

Rotate a Key

Save a Schema and Cred Def

Issue a Credential

Negotiate a Proof

Send a Secure Message

1、Write a DID and Query Its Verkey

Indy-SDK Developer Walkthrough #1, Java Edition

[ Python | .NET | Node.js | Objective C ]

Prerequisites

Setup your workstation with an indy development virtual machine (VM). See prerequisites.

Steps

Step 1

In your normal workstation operating system (not the VM), open a java editor of your choice and paste the code from template.java into a new doc. We will be modifying this code in later steps.

Save the doc as WriteDIDAndQueryVerkey.java

This is a very simple app framework into which you’ll plug the code you’ll be writing.

Step 2

Now we need to give the SDK some context that it will need to deal with an indy ledger. This requires us to point the SDK at some genesis transactions that tell the SDK how to contact the ledger on the network, and how to trust that the nodes it contacts possess appropriate keys.

We also need to create an identity wallet, so the SDK can store the DID and key material generated during the tutorial.

在这里插入图片描述

Copy the contents of step2.java into WriteDIDAndQueryVerkey.java on top of the Step 2 code goes here placeholder comment.Save the updated version of WriteDIDAndQueryVerkey.java.

Study the changes. Scaffolding code like this is likely to appear in anything that uses indy.

Step 3

Now we need to put some DIDs and keys in our identity wallet. Copy the contents of step3.java into WriteDIDAndQueryVerkey.java on top of the Step 3 code goes here placeholder comment.Save the updated version of WriteDIDAndQueryVerkey.java.

Study the changes.

A few operations in indy can only be done by identities (DIDs) with special roles. For example, an DID that is a steward can add a node (the one they own) to the validator pool, and can create DIDs with a trust anchor role. A trust anchor DID can add arbitrary DIDs to the ledger.

Here, we are populating our identity wallet with DID+keypair material for one steward identity and one trust anchor identity. The steward identity is a bootstrapping step, whereas the trust anchor DID is the one we will query later.

Notice that the steward DID is created with a seed, but the trust anchor DID is not. This is because the steward DID and its verkey are already in the ledger; they were part of the genesis transactions we told the SDK to start with in the previous step. But we have to also put the DID, verkey, and private signing key (which the ledger doesn’t know) into our wallet, so we can use the signing key to submit an acceptably signed transaction to the ledger. We will use this steward’s signing key to create our next DID–the one for our trust anchor, which is truly new. This is why we use a hard-coded seed when creating the steward DID–it guarantees that the same DID and key material are created that the genesis transactions expect. In a production indy pool such as the Sovrin “live” network, the bootstrapping steward identities would not have known the seeds.

Step 4

Now that preparations are complete, we can finally write the DID and verkey for our trust anchor identity to the ledger.

Copy the contents of step4.java into WriteDIDAndQueryVerkey.java on top of the Step 4 code goes here placeholder comment.Save the updated version of WriteDIDAndQueryVerkey.java.

Step 5

Once we have an identity on the ledger, we can query it.

Copy the contents of step5.java into WriteDIDAndQueryVerkey.java on top of the Step 5 code goes here placeholder comment.Save the updated version of WriteDIDAndQueryVerkey.java.

Only a handful of lines of code matter to our goal here; the rest of this block is comments and boilerplate cleanup (which you should not omit!). You should see similarities between the way this query “transaction” and the preceding write transaction are bundled and sent.

Step 6

Run the completed demo and observe the whole sequence.

More experiments

Most of the code in this how-to exists to satisfy some preconditions. Now that you have a trust anchor identity, you can write or query any number of additional identities to the ledger, with just a handful of lines of code. Try creating some.

You might try the “Rotate a Key” how-to, which can be done in only once step one you complete this one.

You could also try to create a new steward identity without a seed, or with a different seed, and see what kind of error you get. Only identities with a trustee role can create stewards.

import org.hyperledger.indy.sdk.did.Did;
import org.hyperledger.indy.sdk.did.DidResults;
import org.hyperledger.indy.sdk.pool.Pool;
import org.hyperledger.indy.sdk.wallet.Wallet;
import org.json.JSONObject;

import static org.hyperledger.indy.sdk.ledger.Ledger.*;


/*
Example demonstrating how to add DID with the role of Trust Anchor as Steward.

Uses seed to obtain Steward's DID which already exists on the ledger.
Then it generates new DID/Verkey pair for Trust Anchor.
Using Steward's DID, NYM transaction request is built to add Trust Anchor's DID and Verkey
on the ledger with the role of Trust Anchor.
Once the NYM is successfully written on the ledger, it generates new DID/Verkey pair that represents
a client, which are used to create GET_NYM request to query the ledger and confirm Trust Anchor's Verkey.

For the sake of simplicity, a single wallet is used. In the real world scenario, three different wallets
would be used and DIDs would be exchanged using some channel of communication
*/


public class WriteDIDAndQueryVerkey {
   
	static void demo() throws Exception {
   
        String walletName = "myWallet";
        String poolName = "pool";
        String stewardSeed = "000000000000000000000000Steward1";
        String poolConfig = "{\"genesis_txn\": \"/home/vagrant/code/evernym/indy-sdk/cli/docker_pool_transactions_genesis\"}";


        // Tell SDK which pool you are going to use. You should have already started
        // this pool using docker compose or similar.
        System.out.println("\n1. Creating a new local pool ledger configuration that can be used later to connect pool nodes.\n");
        Pool.createPoolLedgerConfig(poolName, poolConfig).get();

        System.out.println("\n2. Open pool ledger and get the pool handle from libindy.\n");
        Pool pool = Pool.openPoolLedger(poolName, "{}").get();

        System.out.println("\n3. Creates a new identity wallet\n");
        Wallet.createWallet(poolName, walletName, "default", null, null).get();

        System.out.println("\n4. Open identity wallet and get the wallet handle from libindy\n");
        Wallet walletHandle = Wallet.openWallet(walletName, null, null).get();


        // First, put a steward DID and its keypair in the wallet. This doesn't write anything to the ledger,
        // but it gives us a key that we can use to sign a ledger transaction that we're going to submit later.
        System.out.println("\n5. Generating and storing steward DID and Verkey\n");

        // The DID and public verkey for this steward key are already in the ledger; they were part of the genesis
        // transactions we told the SDK to start with in the previous step. But we have to also put the DID, verkey,
        // and private signing key into our wallet, so we can use the signing key to submit an acceptably signed
        // transaction to the ledger, creating our *next* DID (which is truly new). This is why we use a hard-coded seed
        // when creating this DID--it guarantees that the same DID and key material are created that the genesis txns
        // expect.
        String did_json = "{\"seed\": \"" + stewardSeed + "\"}";
        DidResults.CreateAndStoreMyDidResult stewardResult = Did.createAndStoreMyDid(walletHandle, did_json).get();
        String defaultStewardDid = stewardResult.getDid();
        System.out.println("Steward DID: " + defaultStewardDid);
        System.out.println("Steward Verkey: " + stewardResult.getVerkey());

        // Now, create a new DID and verkey for a trust anchor, and store it in our wallet as well. Don't use a seed;
        // this DID and its keyas are secure and random. Again, we're not writing to the ledger yet.
        System.out.println("\n6. Generating and storing Trust Anchor DID and Verkey\n");
        DidResults.CreateAndStoreMyDidResult trustAnchorResult = Did.createAndStoreMyDid(walletHandle, "{}").get();
        String trustAnchorDID = trustAnchorResult.getDid();
        String trustAnchorVerkey = trustAnchorResult.getVerkey();
        System.out.println("Trust anchor DID: " + trustAnchorDID);
        System.out.println("Trust anchor Verkey: " + trustAnchorVerkey);


        // Here, we are building the transaction payload that we'll send to write the Trust Anchor identity to the ledger.
        // We submit this transaction under the authority of the steward DID that the ledger already recognizes.
        // This call will look up the private key of the steward DID in our wallet, and use it to sign the transaction.
        System.out.println("\n7. Build NYM request to add Trust Anchor to the ledger\n");
        String nymRequest = buildNymRequest(defaultStewardDid, trustAnchorDID, trustAnchorVerkey, null, "TRUST_ANCHOR").get();
        System.out.println("NYM request JSON:\n" + nymRequest);

        // Now that we have the transaction ready, send it. The building and the sending are separate steps because some
        // clients may want to prepare transactions in one piece of code (e.g., that has access to privileged backend systems),
        // and communicate with the ledger in a different piece of code (e.g., that lives outside the safe internal
        // network).
        System.out.println("\n8. Sending the nym request to ledger\n");
        String nymResponseJson = signAndSubmitRequest(pool, walletHandle, defaultStewardDid, nymRequest).get();
        System.out.println("NYM transaction response:\n" + nymResponseJson);

        // At this point, we have successfully written a new identity to the ledger. Our next step will be to query it.


        // Here we are creating a third DID. This one is never written to the ledger, but we do have to have it in the
        // wallet, because every request to the ledger has to be signed by some requester. By creating a DID here, we
        // are forcing the wallet to allocate a keypair and identity that we can use to sign the request that's going
        // to read the trust anchor's info from the ledger.
        System.out.println("\n9. Generating and storing DID and Verkey to query the ledger with\n");
        DidResults.CreateAndStoreMyDidResult clientResult = Did.createAndStoreMyDid(walletHandle, "{}").get();
        String clientDID = clientResult.getDid();
        String clientVerkey = clientResult.getVerkey();
        System.out.println("Client DID: " + clientDID);
        System.out.println("Client Verkey: " + clientVerkey);

        System.out.println("\n10. Building the GET_NYM request to query Trust Anchor's Verkey as the Client\n");
        String getNymRequest = buildGetNymRequest(clientDID, trustAnchorDID).get();
        System.out.println("GET_NYM request json:\n" + getNymRequest);

        System.out.println("\n11. Sending the GET_NYM request to the ledger\n");
        String getNymResponse = submitRequest(pool, getNymRequest).get();
        System.out.println("GET_NYM response json:\n" + getNymResponse);

        // See whether we received the same info that we wrote the ledger in step 4.
        System.out.println("\n12. Comparing Trust Anchor Verkey as written by Steward and as retrieved in Client's query\n");
        String responseData = new JSONObject(getNymResponse).getJSONObject("result").getString("data");
        String trustAnchorVerkeyFromLedger = new JSONObject(responseData).getString("verkey");
        System.out.println("Written by Steward: " + trustAnchorVerkey);
        System.out.println("Queried from Ledger: " + trustAnchorVerkeyFromLedger);
        System.out.println("Matching: " + trustAnchorVerkey.equals(trustAnchorVerkeyFromLedger));

        // Do some cleanup.
        System.out.println("\n13. Close and delete wallet\n");
        walletHandle.closeWallet().get();
        Wallet.deleteWallet(walletName, null).get();

        System.out.println("\n14. Close pool\n");
        pool.closePoolLedger().get();

        System.out.println("\n15. Delete pool ledger config\n");
        Pool.deletePoolLedgerConfig(poolName).get();
	}
}


2、Rotate a Key

Indy-SDK Developer Walkthrough #2, Java Edition

[ Python | .NET | Node.js | Objective C ]

Prerequisites

Setup your workstation with an indy development virtual machine (VM). See prerequisites.

Steps

Step 1

In your normal workstation operating system (not the VM), open a java editor of your choice and paste the code from template.java into a new doc. We will be modifying this code in later steps.

Save the doc as RotateKey.java.

Step 2

This how-to builds on the work in “Write DID and Query Verkey”. Rather than duplicate our explanation of those steps here, we will simply copy that code as our starting point.

Copy the contents of step2.java into RotateKey.java on top of the Step 2 code goes here placeholder comment.Save the updated version of RotateKey.java.

Step 3

Once we have an identity on the ledger, we can rotate its key pair.

Copy the contents of step3.java into RotateKey.java on top of the Step 3 code goes here placeholder comment.Save the updated version of RotateKey.java.Most of the logic here should be self-explanatory. However, it’s worth explaining the paired functions replaceKeysStart() and replaceKeysApply(). When we submit the update transaction to the ledger, we have to sign it using the current signing key; the ledger will verify this using the verkey that it recognizes. Yet we have to specify the new verkey value in the transaction itself. The replaceKeysStart() method tells the wallet that an update is pending, and that it should track both the new and old keypairs for the identity. The replaceKeysApply() resolves the pending status so the new value becomes canonical in the local wallet (after it has already become canonical on the ledger).

Step 4

Now we can query the ledger to see which verkey it has on record for the identity.

Copy the contents of step4.java into RotateKey.java on top of the Step 4 code goes here placeholder comment.Save the updated version of RotateKey.java.

Only a handful of lines of code matter to our goal here; the rest of this block is comments and boilerplate cleanup (which you should not omit!).

Step 5

Run the completed demo and observe the whole sequence.

More experiments

TBD

import org.hyperledger.indy.sdk.did.Did;
import org.hyperledger.indy.sdk.did.DidJSONParameters;
import org.hyperledger.indy.sdk.did.DidResults;
import org.hyperledger.indy.sdk.pool.Pool;
import org.hyperledger.indy.sdk.wallet.Wallet;
import org.json.JSONObject;
import utils.PoolUtils;

import java.util.HashMap;
import java.util.Map;

import static org.hyperledger.indy.sdk.anoncreds.Anoncreds.issuerCreateAndStoreClaimDef;
import static org.hyperledger.indy.sdk.ledger.Ledger.*;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值