账户接口

创建账户

说明

体验链暂不支持调用接口的方式来创建账户,仅支持在控制台进行创建。

createAccount

创建账户,同步方式调用。

  • 函数原型

public CreateAccountResponse createAccount(CreateAccountRequest request)
  • 请求参数

参数

必选

类型

说明

request

true

CreateAccountRequest

创建账户的请求

CreateAccountRequest

创建账户的参数:

参数名

必选

类型

说明

account

true

Account

被创建的账户

accountId

true

Identity

创建者的账户 ID

Account,具体参数见下表。

参数

必选

类型

说明

id

true

Identity

被创建账户的ID

balance

false

BigInteger

账户的余额

authMap

true

AuthMap

公钥及其对应的权重信息

recoverKey

true

PublicKey

恢复密钥的公钥

recoverTimestamp

false

long

上一次恢复的时间戳

status

false

AccountStatus

账户的状态:

  • NORMAL(0)

  • FREEZE(1)

  • RECOVERING(2)

encryptionKey

false

byte[]

加密密钥

hashTypeEnum

false

HashTypeEnum

账户的hash类型:

  • SHA256(0)

  • SM3(1)

  • Keccak(2)

说明

创建账户时balance参数需要填0,如果要进行转账,请在创建账户成功后,单独调用转账的接口。

  • 返回字段

返回字段

字段类型

说明

result

CreateAccountResponse

创建账户的响应

CreateAccountResponse,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

TransactionReceipt,具体参数见下表。

参数

类型

说明

result

long

交易执行结果,0 代表成功,其他值代表失败

gasUsed

BigInteger

交易执行所花费的gas费用

logs

List<logEntry>

交易结果日志输出

output

byte[]

交易的输出,此处为虚拟机的执行结果

LogEntry,具体参数见下表。

参数

类型

说明

from

Identity

交易结果日志中的字段,代表交易发送者

to

Identity

交易结果日志中的字段,代表交易接收者

topics

List<String>

交易结果日志中的字段,交易执行的事件主题

logData

byte[]

交易结果日志中的字段,交易执行中的日志数据

  • 示例

public void createAccount() throws IOException {
        // build account
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        Account account = new Account();
        account.setIdentity(userIdentity);
        account.setBalance(BigInteger.ZERO);
        account.setStatus(AccountStatus.NORMAL);
        AuthMap authMap = new AuthMap();
        Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
        //从src/main/resource目录下user.key文件中读取内容,user.key内容的生成方式,见本文档底部的附录内容
        Keypair keypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/user.key")), keyPassword);
        account.setAuthMap(authMap.updateAuth(new PublicKey(keypair), 100));
        //从src/main/resource目录下recovery_user.key文件中读取内容,recovery_user.key内容的生成方式,见本文档底部的附录内容
        Keypair keypairRecovery = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/recovery_user.key")), keyPassword);
        account.setRecoverKey(new PublicKey(keypairRecovery));
        CreateAccountRequest createAccountRequest = new CreateAccountRequest(Utils.getIdentityByName("Administrator"), account);
        // create testAccount
        CreateAccountResponse createAccountResponse = sdk.getAccountService().createAccount(createAccountRequest);
        if (!createAccountResponse.isSuccess()) {
            logger.error("createAccount failed, errorCode :{}, errorDesc: {}", createAccountResponse.getErrorCode().getErrorCode(), createAccountResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = createAccountResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("createAccount failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("createAccount success.返回信息: {}", transactionReceipt.toString());
            }
        }
    }

asyncCreateAccount

创建账户,异步方式调用。

  • 函数原型

public int asyncCreateAccount(CreateAccountRequest request, IAsyncCallback callback)
  • 请求参数

参数

必选

类型

说明

request

true

CreateAccountRequest

创建账户的请求

callback

true

IAsyncCallback

回调函数

CreateAccountRequest,具体参数见下表。

参数名

必选

类型

说明

account

true

Account

被创建的账户

accountId

true

Identity

创建者的账户 ID

其中Account对象的属性,如下表所示。

参数

必选

类型

说明

id

true

Identity

被创建账户的ID

balance

false

BigInteger

账户的余额

authMap

true

AuthMap

公钥及其对应的权重信息

recoverKey

true

PublicKey

恢复密钥的公钥

recoverTimestamp

false

long

上一次恢复的时间戳

status

false

AccountStatus

账户的状态:

  • NORMAL(0)

  • FREEZE(1)

  • RECOVERING(2)

encryptionKey

false

byte[]

加密密钥

hashTypeEnum

false

HashTypeEnum

账户的hash类型:

  • SHA256(0)

  • SM3(1)

  • Keccak(2)

说明

创建账户时balance参数需要填0,如果要进行转账,请在创建账户成功后,单独调用转账的接口。

  • 同步返回字段

返回字段

字段类型

说明

result

int

发送返回值。

  • 异步返回字段

返回字段

字段类型

说明

errorCode

int

SDK发送消息返回的错误码,success时为0。

response

Response

平台返回的响应,其中 response.getErrorCode()是平台返回的错误码。

(CreateAccountResponse)Response,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

  • 示例

public void asyncCreateAccount() throws IOException {
        // build account
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        Account account = new Account();
        account.setIdentity(userIdentity);
        account.setBalance(BigInteger.ZERO);
        account.setStatus(AccountStatus.NORMAL);
        AuthMap authMap = new AuthMap();
        Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
        //从src/main/resource目录下user.key文件中读取内容,user.key内容的生成方式,见本文档底部的附录内容
        Keypair keypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/user.key")), keyPassword);
        account.setAuthMap(authMap.updateAuth(new PublicKey(keypair), 100));
        //从src/main/resource目录下recovery_user.key文件中读取内容,recovery_user.key内容的生成方式,见本文档底部的附录内容
        Keypair keypairRecovery = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/recovery_user.key")), keyPassword);
        account.setRecoverKey(new PublicKey(keypairRecovery));
        // 构建request
        CreateAccountRequest createAccountRequest = new CreateAccountRequest(adminAccount.getIdentity(), account);
        // 创建账号
        int result = sdk.getAccountService().asyncCreateAccount(
                createAccountRequest, new IAsyncCallback() {
                    @Override
                    public void onResponse(int errorCode, Response response) {
                        // 参考错误信息说明文档,检查返回的数据
                        CreateAccountResponse createAccountResponse = (CreateAccountResponse) response;
                        if (!createAccountResponse.isSuccess()) {
                            logger.error("createAccount failed, errorCode :{}, errorDesc: {}", createAccountResponse.getErrorCode().getErrorCode(), createAccountResponse.getErrorCode().getErrorDesc());
                        } else {
                            // 交易收据
                            TransactionReceipt transactionReceipt = createAccountResponse.getTransactionReceipt();
                            if (transactionReceipt.getResult() != 0) {
                                logger.error("createAccount failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                            } else {
                                logger.info("createAccount success.返回信息: {}", transactionReceipt.toString());
                            }
                        }
                    }
                });
    }

转账

transferBalance

交易转帐,同步方式调用。

  • 函数原型

public TransferBalanceResponse transferBalance(TransferBalanceRequest request)
  • 请求参数

参数

必选

类型

说明

request

true

TransferBalanceRequest

交易转帐的请求

TransferBalanceRequest,具体参数见下表。

参数

必选

类型

说明

id

true

Identity

转出账户

receiverId

true

Identity

转入账户

amount

true

BigInteger

转账金额

  • 返回字段

返回字段

字段类型

说明

TransferBalanceResponse

TransferBalanceResponse

交易转账的响应

TransferBalanceResponse,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void transferBalance() {
        // identity 账号ID
        String accountName = "tester";
        Identity toIdentity = Utils.getIdentityByName(accountName);
        BigInteger transferAmount = BigInteger.valueOf(100);
        TransferBalanceRequest transferBalanceRequest = new TransferBalanceRequest(adminAccount.getIdentity(), toIdentity, transferAmount);
        // transfer balance
        // 参考错误信息说明文档,检查返回的数据
        TransferBalanceResponse transferBalanceResponse = sdk.getAccountService().transferBalance(transferBalanceRequest);
        if (!transferBalanceResponse.isSuccess()) {
            logger.error("transferBalance failed, errorCode :{}, errorDesc: {}", transferBalanceResponse.getErrorCode().getErrorCode(), transferBalanceResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = transferBalanceResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("transferBalance failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("transferBalance success.返回信息: {}", transactionReceipt.toString());
            }
        }
    }

asyncTransferBalance

交易转帐,异步方式调用。

  • 函数原型

public int asyncTransferBalance(TransferBalanceRequest request, IAsyncCallback callback)
  • 请求参数

参数

必选

类型

说明

request

true

TransferBalanceRequest

交易转帐的请求

callback

true

IAsyncCallback

回调函数

TransferBalanceRequest,具体参数见下表。

参数

必选

类型

说明

id

true

Identity

转出账户

receiverId

true

Identity

转入账户

amount

true

BigInteger

转账金额

  • 同步返回字段

返回字段

字段类型

说明

result

int

发送返回值

  • 异步返回字段

返回字段

字段类型

说明

errorCode

int

SDK发送消息返回的错误码,success时为0。

response

Response

平台返回的响应,其中 response.getErrorCode()是平台返回的错误码。

(TransferBalanceResponse)Response,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void asyncTransferBalance() {
        // identity 账号ID
        String accountName = "tester";
        Identity toIdentity = Utils.getIdentityByName(accountName);
        BigInteger transferAmount = BigInteger.valueOf(100);
        TransferBalanceRequest transferBalanceRequest = new TransferBalanceRequest(adminAccount.getIdentity(), toIdentity, transferAmount);
        // async transfer balance
        int result = sdk.getAccountService().asyncTransferBalance(transferBalanceRequest, new IAsyncCallback() {
            @Override
            public void onResponse(int errorCode, Response response) {
                // 参考错误信息说明文档,检查返回的数据
                TransferBalanceResponse transferBalanceResponse = (TransferBalanceResponse) response;
                if (!transferBalanceResponse.isSuccess()) {
                    logger.error("transferBalance failed, errorCode :{}, errorDesc: {}", transferBalanceResponse.getErrorCode().getErrorCode(), transferBalanceResponse.getErrorCode().getErrorDesc());
                } else {
                    // 交易收据
                    TransactionReceipt transactionReceipt = transferBalanceResponse.getTransactionReceipt();
                    if (transactionReceipt.getResult() != 0) {
                        logger.error("transferBalance failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                    } else {
                        logger.info("transferBalance success.返回信息: {}", transactionReceipt.toString());
                    }
                }
            }
        });
    }

设置恢复公钥

setRecoverKey

设置恢复公钥,同步方式调用。

  • 函数原型

public SetRecoverKeyResponse setRecoverKey(SetRecoverKeyRequest request)
  • 请求参数

参数

必选

类型

说明

request

true

SetRecoverKeyRequest

恢复公钥的请求

SetRecoverKeyRequest,具体参数见下表。

参数

必选

类型

说明

acctId

true

Identity

要设置的账户 ID

recoverPubKey

true

PublicKey

新的恢复公钥

  • 返回字段

返回字段

字段类型

说明

response

SetRecoverKeyResponse

恢复公钥的响应

SetRecoverKeyResponse,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void setRecoverKey() throws IOException {
        // identity 账号ID
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
        Keypair keypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/tester.key")), keyPassword);
        PublicKey recoverKey = new PublicKey(keypair);
        SetRecoverKeyRequest request = new SetRecoverKeyRequest(userIdentity, recoverKey);

        SetRecoverKeyResponse setRecoverKeyResponse = sdk.getAccountService().setRecoverKey(request);
        if (!setRecoverKeyResponse.isSuccess()) {
            logger.error("setRecoverKey failed, errorCode :{}, errorDesc: {}", setRecoverKeyResponse.getErrorCode().getErrorCode(), setRecoverKeyResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = setRecoverKeyResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("setRecoverKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("setRecoverKey success.返回信息: {}", transactionReceipt.toString());
            }
        }
    }

asyncSetRecoverKey

设置恢复公钥,异步方式调用。

  • 函数原型

public int asyncSetRecoverKey(SetRecoverKeyRequest request, IAsyncCallback callback)
  • 请求参数

参数

必选

类型

说明

request

true

SetRecoverKeyRequest

恢复公钥的请求

callback

true

IAsyncCallback

回调函数

SetRecoverKeyRequest

重置恢复公钥的参数:

参数

必选

类型

说明

acctId

true

Identity

要设置的账户 ID

recoverPubKey

true

PublicKey

新的恢复公钥

  • 同步返回字段

返回字段

字段类型

说明

result

int

发送返回值

  • 异步返回字段

返回字段

字段类型

说明

errorCode

int

SDK发送消息返回的错误码,success时为0。

response

Response

平台返回的响应,其中 response.getErrorCode()是平台返回的错误码。

(SetRecoverKeyResponse)Response,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void asyncSetRecover() throws IOException {
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
        Keypair keypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/tester.key")), keyPassword);
        PublicKey recoverKey = new PublicKey(keypair);
        SetRecoverKeyRequest request = new SetRecoverKeyRequest(userIdentity, recoverKey);
        int result = sdk.getAccountService().asyncSetRecoverKey(
                request,
                new IAsyncCallback() {
                    @Override
                    public void onResponse(int errorCode, Response response) {
                        // 参考错误信息说明文档,检查返回的数据
                        SetRecoverKeyResponse setRecoverKeyResponse = (SetRecoverKeyResponse) response;
                        if (!setRecoverKeyResponse.isSuccess()) {
                            logger.error("transferBalance failed, errorCode :{}, errorDesc: {}", setRecoverKeyResponse.getErrorCode().getErrorCode(), setRecoverKeyResponse.getErrorCode().getErrorDesc());
                        } else {
                            // 交易收据
                            TransactionReceipt transactionReceipt = setRecoverKeyResponse.getTransactionReceipt();
                            if (transactionReceipt.getResult() != 0) {
                                logger.error("transferBalance failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                            } else {
                                logger.info("transferBalance success.返回信息: {}", transactionReceipt.toString());
                            }
                        }
                    }
                });
    }

预重置公钥

preResetPubKey

预重置公钥,同步方式调用。

  • 函数原型

public PreResetPubKeyResponse preResetPubKey(PreResetPubKeyRequest request)
  • 请求参数

参数

必选

类型

说明

request

true

PreResetPubKeyRequest

预重置公钥的请求

PreResetPubKeyRequest,具体参数见下表。

参数

必选

类型

说明

acctId

true

Identity

要预重置的账户 ID

  • 返回字段

返回字段

字段类型

说明

response

PreResetPubKeyResponse

预重置公钥的响应

PreResetPubKeyResponse,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void preResetPubKey() throws IOException {
        // 获取账号权重
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        Account account = sdk.getQueryService().queryAccount(userIdentity).getAccount();
        AuthMap beforeAuthMap = account.getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            beforeAuthMap.updateAuth(entry.getKey(), entry.getValue() + 10);
        }

        // pre reset
        PreResetPubKeyRequest preResetPubKeyRequest = new PreResetPubKeyRequest(userIdentity);
        // sign resetPubKeyRequest
        long ts = sdk.getNetwork().getSystemTimestamp();
        preResetPubKeyRequest.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger.valueOf(RandomUtil.randomize(ts + preResetPubKeyRequest.getTransaction().hashCode())), true);
        preResetPubKeyRequest.complete();
        //重置账户权限公钥(必须使用恢复密钥对应的私钥来进行签名,from与to必须相同,value为0)
        ArrayList<SignerBase> signers = new ArrayList<>();
        Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
        Keypair keypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/tester.key")), keyPassword);
        signers.add(MyCrypto.getInstance().createSigner(keypair));
        sdk.getAccountService().signRequest(signers, preResetPubKeyRequest);

        PreResetPubKeyResponse preResetPubKeyResponse = sdk.getAccountService().preResetPubKey(preResetPubKeyRequest);
        // 账户状态将改为RECOVERING
        if (!preResetPubKeyResponse.isSuccess()) {
            logger.error("preResetPubKey failed, errorCode :{}, errorDesc: {}", preResetPubKeyResponse.getErrorCode().getErrorCode(), preResetPubKeyResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = preResetPubKeyResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("preResetPubKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("preResetPubKey success.返回信息: {}", transactionReceipt.toString());
            }
        }

        // reset
        ResetPubKeyRequest resetPubKeyRequest = new ResetPubKeyRequest(userIdentity, beforeAuthMap);
        // sign resetPubKeyRequest
        ts = sdk.getNetwork().getSystemTimestamp();
        resetPubKeyRequest.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger.valueOf(RandomUtil.randomize(ts + resetPubKeyRequest.getTransaction().hashCode())), true);
        resetPubKeyRequest.complete();
        //重置账户权限公钥(必须使用恢复密钥对应的私钥来进行签名,from与to必须相同,value为0)
        signers = new ArrayList<>();
        signers.add(MyCrypto.getInstance().createSigner(keypair));
        sdk.getAccountService().signRequest(signers, resetPubKeyRequest);
        ResetPubKeyResponse resetPubKeyResponse = sdk.getAccountService().resetPublicKey(resetPubKeyRequest);
        // 账户状态恢复为NORMAL
        if (!resetPubKeyResponse.isSuccess()) {
            logger.error("resetPublicKey failed, errorCode :{}, errorDesc: {}", resetPubKeyResponse.getErrorCode().getErrorCode(), resetPubKeyResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = resetPubKeyResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("resetPublicKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("resetPublicKey success.返回信息: {}", transactionReceipt.toString());
            }
        }

        AuthMap afterAuthMap = sdk.getQueryService().queryAccount(userIdentity).getAccount().getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            if (beforeAuthMap.getAuthMap().get(entry.getKey()).equals(afterAuthMap.getAuthMap().get(entry.getKey()))) {
                logger.info("重置结果正确");
            }
        }
    }

asyncPreResetPubKey

预重置公钥,异步方式调用。

  • 函数原型

public int asyncPreResetPubKey(PreResetPubKeyRequest request, IAsyncCallback callback)
  • 请求参数

参数

必选

类型

说明

request

true

PreResetPubKeyRequest

预重置公钥的请求

callback

true

IAsyncCallback

回调函数

PreResetPubKeyRequest

预重置公钥的参数:

参数

必选

类型

说明

acctId

true

Identity

要预重置的账户 ID

  • 同步返回字段

返回字段

字段类型

说明

result

int

发送返回值

  • 异步返回字段

返回字段

字段类型

说明

errorCode

int

SDK发送消息返回的错误码,success时为0。

response

Response

平台返回的响应,其中 response.getErrorCode()是平台返回的错误码。

(PreResetPubKeyResponse)Response,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void asyncPreResetPubKey() throws InterruptedException, IOException {
        // 获取账号权重
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        Account account = sdk.getQueryService().queryAccount(userIdentity).getAccount();
        AuthMap beforeAuthMap = account.getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            beforeAuthMap.updateAuth(entry.getKey(), entry.getValue() + 10);
        }

        // pre reset
        PreResetPubKeyRequest preResetPubKeyRequest = new PreResetPubKeyRequest(userIdentity);
        // sign resetPubKeyRequest
        long ts = sdk.getNetwork().getSystemTimestamp();
        preResetPubKeyRequest.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger.valueOf(RandomUtil.randomize(ts + preResetPubKeyRequest.getTransaction().hashCode())), true);
        preResetPubKeyRequest.complete();
        //重置账户权限公钥(必须使用恢复密钥对应的私钥来进行签名,from与to必须相同,value为0)
        ArrayList<SignerBase> signers = new ArrayList<>();
        Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
        Keypair keypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/tester.key")), keyPassword);
        signers.add(MyCrypto.getInstance().createSigner(keypair));
        sdk.getAccountService().signRequest(signers, preResetPubKeyRequest);
        CountDownLatch countDownLatch = new CountDownLatch(2);
        int result = sdk.getAccountService().asyncPreResetPubKey(preResetPubKeyRequest, new IAsyncCallback() {
            @Override
            public void onResponse(int errorCode, Response response) {
                // 参考错误信息说明文档,检查返回的数据
                PreResetPubKeyResponse preResetPubKeyResponse = (PreResetPubKeyResponse) response;
                // 账户状态将改为RECOVERING
                if (!preResetPubKeyResponse.isSuccess()) {
                    logger.error("preResetPubKey failed, errorCode :{}, errorDesc: {}", preResetPubKeyResponse.getErrorCode().getErrorCode(), preResetPubKeyResponse.getErrorCode().getErrorDesc());
                } else {
                    // 交易收据
                    TransactionReceipt transactionReceipt = preResetPubKeyResponse.getTransactionReceipt();
                    if (transactionReceipt.getResult() != 0) {
                        logger.error("preResetPubKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                    } else {
                        logger.info("preResetPubKey success.返回信息: {}", transactionReceipt.toString());
                    }
                }
                countDownLatch.countDown();
            }
        });

        // reset
        ResetPubKeyRequest resetPubKeyRequest = new ResetPubKeyRequest(userIdentity, beforeAuthMap);
        // sign resetPubKeyRequest
        ts = sdk.getNetwork().getSystemTimestamp();
        resetPubKeyRequest.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger.valueOf(RandomUtil.randomize(ts + resetPubKeyRequest.getTransaction().hashCode())), true);
        resetPubKeyRequest.complete();
        //重置账户权限公钥(必须使用恢复密钥对应的私钥来进行签名,from与to必须相同,value为0)
        signers = new ArrayList<>();
        signers.add(MyCrypto.getInstance().createSigner(keypair));
        sdk.getAccountService().signRequest(signers, resetPubKeyRequest);
        int response = sdk.getAccountService().asyncResetPubKey(
                resetPubKeyRequest,
                new IAsyncCallback() {
                    @Override
                    public void onResponse(int errorCode, Response response) {
                        // 参考错误信息说明文档,检查返回的数据
                        ResetPubKeyResponse resetPubKeyResponse = (ResetPubKeyResponse) response;
                        // 账户状态恢复为NORMAL
                        if (!resetPubKeyResponse.isSuccess()) {
                            logger.error("resetPubKey failed, errorCode :{}, errorDesc: {}", resetPubKeyResponse.getErrorCode().getErrorCode(), resetPubKeyResponse.getErrorCode().getErrorDesc());
                        } else {
                            // 交易收据
                            TransactionReceipt transactionReceipt = resetPubKeyResponse.getTransactionReceipt();
                            if (transactionReceipt.getResult() != 0) {
                                logger.error("resetPubKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                            } else {
                                logger.info("resetPubKey success.返回信息: {}", transactionReceipt.toString());
                            }
                        }
                        countDownLatch.countDown();
                    }
                });

        countDownLatch.await(3, TimeUnit.SECONDS);
        AuthMap afterAuthMap = sdk.getQueryService().queryAccount(userIdentity).getAccount().getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            if (beforeAuthMap.getAuthMap().get(entry.getKey()).equals(afterAuthMap.getAuthMap().get(entry.getKey()))) {
                logger.info("重置结果正确");
            }
        }
    }

重置公钥

resetPublicKey

重置公钥,同步方式调用。

  • 函数原型

public ResetPubKeyResponse resetPublicKey(ResetPubKeyRequest request)
  • 请求参数

参数

必选

类型

说明

request

true

ResetPubKeyRequest

重置公钥的请求

ResetPubKeyRequest,具体参数见下表。

参数

必选

类型

说明

acctId

true

Identity

要重置的账户 ID

authMap

true

AuthMap

账户或者合约的公钥和权重值

  • 返回字段

返回字段

字段类型

说明

response

ResetPubKeyResponse

重置公钥的响应

ResetPubKeyResponse,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void preResetPubKey() throws IOException {
        // 获取账号权重
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        Account account = sdk.getQueryService().queryAccount(userIdentity).getAccount();
        AuthMap beforeAuthMap = account.getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            beforeAuthMap.updateAuth(entry.getKey(), entry.getValue() + 10);
        }

        // pre reset
        PreResetPubKeyRequest preResetPubKeyRequest = new PreResetPubKeyRequest(userIdentity);
        // sign resetPubKeyRequest
        long ts = sdk.getNetwork().getSystemTimestamp();
        preResetPubKeyRequest.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger.valueOf(RandomUtil.randomize(ts + preResetPubKeyRequest.getTransaction().hashCode())), true);
        preResetPubKeyRequest.complete();
        //重置账户权限公钥(必须使用恢复密钥对应的私钥来进行签名,from与to必须相同,value为0)
        ArrayList<SignerBase> signers = new ArrayList<>();
        Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
        Keypair keypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/tester.key")), keyPassword);
        signers.add(MyCrypto.getInstance().createSigner(keypair));
        sdk.getAccountService().signRequest(signers, preResetPubKeyRequest);

        PreResetPubKeyResponse preResetPubKeyResponse = sdk.getAccountService().preResetPubKey(preResetPubKeyRequest);
        // 账户状态将改为RECOVERING
        if (!preResetPubKeyResponse.isSuccess()) {
            logger.error("preResetPubKey failed, errorCode :{}, errorDesc: {}", preResetPubKeyResponse.getErrorCode().getErrorCode(), preResetPubKeyResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = preResetPubKeyResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("preResetPubKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("preResetPubKey success.返回信息: {}", transactionReceipt.toString());
            }
        }

        // reset
        ResetPubKeyRequest resetPubKeyRequest = new ResetPubKeyRequest(userIdentity, beforeAuthMap);
        // sign resetPubKeyRequest
        ts = sdk.getNetwork().getSystemTimestamp();
        resetPubKeyRequest.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger.valueOf(RandomUtil.randomize(ts + resetPubKeyRequest.getTransaction().hashCode())), true);
        resetPubKeyRequest.complete();
        //重置账户权限公钥(必须使用恢复密钥对应的私钥来进行签名,from与to必须相同,value为0)
        signers = new ArrayList<>();
        signers.add(MyCrypto.getInstance().createSigner(keypair));
        sdk.getAccountService().signRequest(signers, resetPubKeyRequest);
        ResetPubKeyResponse resetPubKeyResponse = sdk.getAccountService().resetPublicKey(resetPubKeyRequest);
        // 账户状态恢复为NORMAL
        if (!resetPubKeyResponse.isSuccess()) {
            logger.error("resetPublicKey failed, errorCode :{}, errorDesc: {}", resetPubKeyResponse.getErrorCode().getErrorCode(), resetPubKeyResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = resetPubKeyResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("resetPublicKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("resetPublicKey success.返回信息: {}", transactionReceipt.toString());
            }
        }

        AuthMap afterAuthMap = sdk.getQueryService().queryAccount(userIdentity).getAccount().getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            if (beforeAuthMap.getAuthMap().get(entry.getKey()).equals(afterAuthMap.getAuthMap().get(entry.getKey()))) {
                logger.info("重置结果正确");
            }
        }
    }

asyncResetPubKey

重置公钥,异步方式调用。

  • 函数原型

public int asyncResetPubKey(ResetPubKeyRequest request,IAsyncCallback callback)
  • 请求参数

参数

必选

类型

说明

request

true

ResetPubKeyRequest

重置公钥的请求

callback

true

IAsyncCallback

回调函数

ResetPubKeyRequest,具体参数见下表。

参数

必选

类型

说明

acctId

true

Identity

要重置的账户 ID

authMap

true

AuthMap

账户或者合约的公钥和权重值

  • 同步返回字段

返回字段

字段类型

说明

result

int

发送返回值

  • 异步返回字段

返回字段

字段类型

说明

errorCode

int

SDK发送消息返回的错误码,success时为0。

response

Response

平台返回的响应,其中 response.getErrorCode()是平台返回的错误码。

(ResetPubKeyResponse)Response,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void asyncPreResetPubKey() throws InterruptedException, IOException {
        // 获取账号权重
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        Account account = sdk.getQueryService().queryAccount(userIdentity).getAccount();
        AuthMap beforeAuthMap = account.getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            beforeAuthMap.updateAuth(entry.getKey(), entry.getValue() + 10);
        }

        // pre reset
        PreResetPubKeyRequest preResetPubKeyRequest = new PreResetPubKeyRequest(userIdentity);
        // sign resetPubKeyRequest
        long ts = sdk.getNetwork().getSystemTimestamp();
        preResetPubKeyRequest.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger.valueOf(RandomUtil.randomize(ts + preResetPubKeyRequest.getTransaction().hashCode())), true);
        preResetPubKeyRequest.complete();
        //重置账户权限公钥(必须使用恢复密钥对应的私钥来进行签名,from与to必须相同,value为0)
        ArrayList<SignerBase> signers = new ArrayList<>();
        Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
        Keypair keypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(this.getClass().getClassLoader().getResourceAsStream("/tester.key")), keyPassword);
        signers.add(MyCrypto.getInstance().createSigner(keypair));
        sdk.getAccountService().signRequest(signers, preResetPubKeyRequest);
        CountDownLatch countDownLatch = new CountDownLatch(2);
        int result = sdk.getAccountService().asyncPreResetPubKey(preResetPubKeyRequest, new IAsyncCallback() {
            @Override
            public void onResponse(int errorCode, Response response) {
                // 参考错误信息说明文档,检查返回的数据
                PreResetPubKeyResponse preResetPubKeyResponse = (PreResetPubKeyResponse) response;
                // 账户状态将改为RECOVERING
                if (!preResetPubKeyResponse.isSuccess()) {
                    logger.error("preResetPubKey failed, errorCode :{}, errorDesc: {}", preResetPubKeyResponse.getErrorCode().getErrorCode(), preResetPubKeyResponse.getErrorCode().getErrorDesc());
                } else {
                    // 交易收据
                    TransactionReceipt transactionReceipt = preResetPubKeyResponse.getTransactionReceipt();
                    if (transactionReceipt.getResult() != 0) {
                        logger.error("preResetPubKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                    } else {
                        logger.info("preResetPubKey success.返回信息: {}", transactionReceipt.toString());
                    }
                }
                countDownLatch.countDown();
            }
        });

        // reset
        ResetPubKeyRequest resetPubKeyRequest = new ResetPubKeyRequest(userIdentity, beforeAuthMap);
        // sign resetPubKeyRequest
        ts = sdk.getNetwork().getSystemTimestamp();
        resetPubKeyRequest.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger.valueOf(RandomUtil.randomize(ts + resetPubKeyRequest.getTransaction().hashCode())), true);
        resetPubKeyRequest.complete();
        //重置账户权限公钥(必须使用恢复密钥对应的私钥来进行签名,from与to必须相同,value为0)
        signers = new ArrayList<>();
        signers.add(MyCrypto.getInstance().createSigner(keypair));
        sdk.getAccountService().signRequest(signers, resetPubKeyRequest);
        int response = sdk.getAccountService().asyncResetPubKey(
                resetPubKeyRequest,
                new IAsyncCallback() {
                    @Override
                    public void onResponse(int errorCode, Response response) {
                        // 参考错误信息说明文档,检查返回的数据
                        ResetPubKeyResponse resetPubKeyResponse = (ResetPubKeyResponse) response;
                        // 账户状态恢复为NORMAL
                        if (!resetPubKeyResponse.isSuccess()) {
                            logger.error("resetPubKey failed, errorCode :{}, errorDesc: {}", resetPubKeyResponse.getErrorCode().getErrorCode(), resetPubKeyResponse.getErrorCode().getErrorDesc());
                        } else {
                            // 交易收据
                            TransactionReceipt transactionReceipt = resetPubKeyResponse.getTransactionReceipt();
                            if (transactionReceipt.getResult() != 0) {
                                logger.error("resetPubKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                            } else {
                                logger.info("resetPubKey success.返回信息: {}", transactionReceipt.toString());
                            }
                        }
                        countDownLatch.countDown();
                    }
                });

        countDownLatch.await(3, TimeUnit.SECONDS);
        AuthMap afterAuthMap = sdk.getQueryService().queryAccount(userIdentity).getAccount().getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            if (beforeAuthMap.getAuthMap().get(entry.getKey()).equals(afterAuthMap.getAuthMap().get(entry.getKey()))) {
                logger.info("重置结果正确");
            }
        }
    }

更新权重

updateAuthMap

更新权重,同步方式调用。

  • 函数原型

    public UpdateAuthMapResponse updateAuthMap(UpdateAuthMapRequest request)
  • 请求参数

参数

必选

类型

说明

request

true

UpdateAuthMapRequest

更新权重的请求

UpdateAuthMapRequest,具体参数见下表。

参数

必选

类型

说明

acctId

true

Identity

要设置的账户 ID

authMap

true

AuthMap

新的权重 authmap

  • 返回字段

返回字段

字段类型

说明

response

UpdateAuthMapResponse

更新权重的响应

UpdateAuthMapResponse,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void updateAuthMap() {
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        AuthMap beforeAuthMap = sdk.getQueryService().queryAccount(userIdentity).getAccount().getAuthMap();

        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            beforeAuthMap.updateAuth(entry.getKey(), entry.getValue() + 10);
        }
        UpdateAuthMapRequest updateAuthMapRequest = new UpdateAuthMapRequest(userIdentity, beforeAuthMap);

        // 参考错误信息说明文档,检查返回的数据
        UpdateAuthMapResponse updateAuthMapResponse = sdk.getAccountService().updateAuthMap(updateAuthMapRequest);
        if (!updateAuthMapResponse.isSuccess()) {
            logger.error("updateAuthMap failed, errorCode :{}, errorDesc: {}", updateAuthMapResponse.getErrorCode().getErrorCode(), updateAuthMapResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = updateAuthMapResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("updateAuthMap failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("updateAuthMap success.返回信息: {}", transactionReceipt.toString());
            }
        }

        AuthMap afterAuthMap = sdk.getQueryService().queryAccount(userIdentity).getAccount().getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            if (beforeAuthMap.getAuthMap().get(entry.getKey()).equals(afterAuthMap.getAuthMap().get(entry.getKey()))) {
                logger.info("updateAuthMap 正确");
            }
        }
    }

asyncUpdateAuthMap

更新权重,异步方式调用。

  • 函数原型

public int asyncUpdateAuthMap(UpdateAuthMapRequest request,IAsyncCallback callback)
  • 请求参数

参数

必选

类型

说明

request

true

UpdateAuthMapRequest

更新权重的请求

callback

true

IAsyncCallback

回调函数

UpdateAuthMapRequest,具体参数见下表。

参数

必选

类型

说明

acctId

true

Identity

要设置的账户 ID

authMap

true

AuthMap

新的权重 authmap

  • 同步返回字段

返回字段

字段类型

说明

result

int

发送返回值

  • 异步返回字段

返回字段

字段类型

说明

errorCode

int

SDK发送消息返回的错误码,success时为0。

response

Response

平台返回的响应,其中 response.getErrorCode()是平台返回的错误码。

(UpdateAuthMapResponse)Response,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void asyncUpdateAuthMap() throws InterruptedException {
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        AuthMap beforeAuthMap = sdk.getQueryService().queryAccount(userIdentity).getAccount().getAuthMap();

        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            beforeAuthMap.updateAuth(entry.getKey(), entry.getValue() + 10);
        }
        UpdateAuthMapRequest updateAuthMapRequest = new UpdateAuthMapRequest(userIdentity, beforeAuthMap);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        int result = sdk.getAccountService().asyncUpdateAuthMap(
                updateAuthMapRequest,
                new IAsyncCallback() {
                    @Override
                    public void onResponse(int errorCode, Response response) {
                        // 参考错误信息说明文档,检查返回的数据
                        UpdateAuthMapResponse updateAuthMapResponse = (UpdateAuthMapResponse) response;
                        if (!updateAuthMapResponse.isSuccess()) {
                            logger.error("updateAuthMap failed, errorCode :{}, errorDesc: {}", updateAuthMapResponse.getErrorCode().getErrorCode(), updateAuthMapResponse.getErrorCode().getErrorDesc());
                        } else {
                            // 交易收据
                            TransactionReceipt transactionReceipt = updateAuthMapResponse.getTransactionReceipt();
                            if (transactionReceipt.getResult() != 0) {
                                logger.error("updateAuthMap failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                            } else {
                                logger.info("updateAuthMap success.返回信息: {}", transactionReceipt.toString());
                            }
                        }
                        countDownLatch.countDown();
                    }
                });
        countDownLatch.await(2, TimeUnit.SECONDS);
        AuthMap afterAuthMap = sdk.getQueryService().queryAccount(userIdentity).getAccount().getAuthMap();
        for (Map.Entry<PublicKey, Integer> entry : beforeAuthMap.getAuthMap().entrySet()) {
            if (beforeAuthMap.getAuthMap().get(entry.getKey()).equals(afterAuthMap.getAuthMap().get(entry.getKey()))) {
                logger.info("updateAuthMap 正确");
            }
        }
    }

冻结账户

freezeAccount

冻结账户,同步方式调用。

  • 函数原型

public FreezeAccountResponse freezeAccount(FreezeAccountRequest request)
  • 请求参数

参数

必选

类型

说明

request

true

FreezeAccountRequest

冻结账户的请求

FreezeAccountRequest,具体参数见下表。

参数

必选

类型

说明

id

true

Identity

冻结账户的操作者 ID,可以为当前账户或者admin账户

frozenId

true

Identity

待冻结的账户 ID

  • 返回字段

返回字段

字段类型

说明

response

FreezeAccountResponse

冻结账户的响应

FreezeAccountResponse,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void freezeAccount() {
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        FreezeAccountRequest freezeAccountRequest = new FreezeAccountRequest(userIdentity, userIdentity);
        FreezeAccountResponse freezeAccountResponse = sdk.getAccountService().freezeAccount(freezeAccountRequest);
        if (!freezeAccountResponse.isSuccess()) {
            logger.error("freezeAccount failed, errorCode :{}, errorDesc: {}", freezeAccountResponse.getErrorCode().getErrorCode(), freezeAccountResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = freezeAccountResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("freezeAccount failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("freezeAccount success.返回信息: {}", transactionReceipt.toString());
            }
        }
    }

asyncFreezeAccount

冻结账户,异步方式调用。

  • 函数原型

public int asyncFreezeAccount(FreezeAccountRequest request,IAsyncCallback callback)
  • 请求参数

参数

必选

类型

说明

request

true

FreezeAccountRequest

冻结账户的请求

callback

true

IAsyncCallback

回调函数

FreezeAccountRequest,具体参数见下表。

参数

必选

类型

说明

id

true

Identity

冻结账户的操作者 ID,可以为当前账户或者admin账户

frozenId

true

Identity

待冻结的账户 ID

  • 同步返回字段

返回字段

字段类型

说明

result

int

发送返回值

  • 异步返回字段

返回字段

字段类型

说明

errorCode

int

SDK发送消息返回的错误码,success时为0。

response

Response

平台返回的响应,其中 response.getErrorCode()是平台返回的错误码。

(FreezeAccountResponse)Response,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void asyncFreezeAccount() {
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        FreezeAccountRequest freezeAccountRequest = new FreezeAccountRequest(userIdentity, userIdentity);
        int result = sdk.getAccountService().asyncFreezeAccount(
                freezeAccountRequest
                , new IAsyncCallback() {
                    @Override
                    public void onResponse(int errorCode, Response response) {
                        // 参考错误信息说明文档,检查返回的数据
                        FreezeAccountResponse freezeAccountResponse = (FreezeAccountResponse) response;
                        if (!freezeAccountResponse.isSuccess()) {
                            logger.error("freezeAccount failed, errorCode :{}, errorDesc: {}", freezeAccountResponse.getErrorCode().getErrorCode(), freezeAccountResponse.getErrorCode().getErrorDesc());
                        } else {
                            // 交易收据
                            TransactionReceipt transactionReceipt = freezeAccountResponse.getTransactionReceipt();
                            if (transactionReceipt.getResult() != 0) {
                                logger.error("freezeAccount failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                            } else {
                                logger.info("freezeAccount success.返回信息: {}", transactionReceipt.toString());
                            }
                        }
                    }
                });
    }

更新加密密钥

updateEncryptionKey

更新加密密钥,同步方式调用。

  • 函数原型

public UpdateEncryptionKeyResponse updateEncryptionKey(UpdateEncryptionKeyRequest request)
  • 请求参数

参数

必选

类型

说明

request

true

UpdateEncryptionKeyRequest

更新加密密钥的请求。

UpdateEncryptionKeyRequest,具体参数如下。

参数

必选

类型

说明

acctId

true

Identity

更新密钥的操作者 ID

encryptionKey

true

byte[]

密钥

  • 返回字段

返回字段

字段类型

说明

response

UpdateEncryptionKeyResponse

更新加密密钥的响应。

UpdateEncryptionKeyResponse,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void updateEncryptionKey() {
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        UpdateEncryptionKeyRequest updateEncryptionKeyRequest = new UpdateEncryptionKeyRequest(userIdentity, new byte[10]);

        UpdateEncryptionKeyResponse updateEncryptionKeyResponse = sdk.getAccountService().updateEncryptionKey(updateEncryptionKeyRequest);
        if (!updateEncryptionKeyResponse.isSuccess()) {
            logger.error("updateEncryptionKey failed, errorCode :{}, errorDesc: {}", updateEncryptionKeyResponse.getErrorCode().getErrorCode(), updateEncryptionKeyResponse.getErrorCode().getErrorDesc());
        } else {
            // 交易收据
            TransactionReceipt transactionReceipt = updateEncryptionKeyResponse.getTransactionReceipt();
            if (transactionReceipt.getResult() != 0) {
                logger.error("updateEncryptionKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
            } else {
                logger.info("updateEncryptionKey success.返回信息: {}", transactionReceipt.toString());
            }
        }
    }

asyncUpdateEncryptionKey

更新加密密钥,异步方式调用。

  • 函数原型

public int asyncUpdateEncryptionKey(UpdateEncryptionKeyRequest request,IAsyncCallback callback)
  • 请求参数

参数

必选

类型

说明

request

true

UpdateEncryptionKeyRequest

更新加密密钥的请求。

callback

true

IAsyncCallback

回调函数

UpdateEncryptionKeyRequest,具体参数见下表。

参数

必选

类型

说明

acctId

true

Identity

更新密钥的操作者 ID

encryptionKey

true

byte[]

密钥

  • 同步返回字段

返回字段

字段类型

说明

result

int

发送返回值

  • 异步返回字段

返回字段

字段类型

说明

errorCode

int

SDK发送消息返回的错误码,success时为0。

response

Response

平台返回的响应,其中 response.getErrorCode()是平台返回的错误码。

(UpdateEncryptionKeyResponse)Response,具体参数见下表。

参数

类型

说明

transactionReceipt

TransactionReceipt

交易收据

blockNumber

BigInteger

区块号

txIndex

int

交易偏移量

txHash

Hash

交易hash

isLocalTransaction

boolean

是否为本地交易

  • 示例

public void asyncUpdateEncryptionKey() {
        String accountName = "tester";
        Identity userIdentity = Utils.getIdentityByName(accountName);
        UpdateEncryptionKeyRequest updateEncryptionKeyRequest = new UpdateEncryptionKeyRequest(userIdentity, new byte[10]);
        int result = sdk.getAccountService().asyncUpdateEncryptionKey(
                updateEncryptionKeyRequest,
                new IAsyncCallback() {
                    @Override
                    public void onResponse(int errorCode, Response response) {
                        // 参考错误信息说明文档,检查返回的数据
                        UpdateEncryptionKeyResponse updateEncryptionKeyResponse = (UpdateEncryptionKeyResponse) response;
                        if (!updateEncryptionKeyResponse.isSuccess()) {
                            logger.error("updateEncryptionKey failed, errorCode :{}, errorDesc: {}", updateEncryptionKeyResponse.getErrorCode().getErrorCode(), updateEncryptionKeyResponse.getErrorCode().getErrorDesc());
                        } else {
                            // 交易收据
                            TransactionReceipt transactionReceipt = updateEncryptionKeyResponse.getTransactionReceipt();
                            if (transactionReceipt.getResult() != 0) {
                                logger.error("updateEncryptionKey failed, errorCode :{}, errorDesc: {}", ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorCode(), ErrorCode.valueOf((int) transactionReceipt.getResult()).getErrorDesc());
                            } else {
                                logger.info("updateEncryptionKey success.返回信息: {}", transactionReceipt.toString());
                            }
                        }
                    }
                });
    }

附录:user.key和recovery_user.key的内容生成

以下为user.keyrecovery_user.key的内容生成方式,用户可以新建一个名为user.keyrecovery_user.key的文件,将下面获取的内容复制进去,放置在项目中使用。

Demo

说明

私钥为ecc编码格式。

import com.alipay.demo.util.CryptUtils;

import java.io.ByteArrayOutputStream;
import java.security.KeyPair;
/**
 *  @Description: 生成user.key和recovery_user.key
 */
public class UserKeyGen {
    public static void main(String[] args) throws Exception {
        //是否是国密链
        boolean isSm = false;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayOutputStream byteArrayOutputStreamRec = new ByteArrayOutputStream();

        KeyPair keyPair;
        KeyPair keyPairRec;
        String userKeyPassword = "12****";
        String recoverKeyPassword = "123****"; //推荐和userKeyPassword不一样
        if (isSm) {
            //国密链的写法
            keyPair = CryptUtils.generateEncryptedSmPrivateKey(userKeyPassword, true, byteArrayOutputStream);
            keyPairRec = CryptUtils.generateEncryptedSmPrivateKey(recoverKeyPassword, true, byteArrayOutputStreamRec);
        } else {
            //普通合约链的写法
            keyPair = CryptUtils.generateEncryptedEcck1PrivateKey(userKeyPassword, true, byteArrayOutputStream);
            keyPairRec = CryptUtils.generateEncryptedEcck1PrivateKey(recoverKeyPassword, true, byteArrayOutputStreamRec);
        }

        System.out.println("user.key: \n" + new String(byteArrayOutputStream.toByteArray()));
        System.out.println("pub.txt: \n" + new String(CryptUtils.getPublicKeyString(keyPair).getBytes()));
        System.out.println("recovery_user.key: \n" + new String(byteArrayOutputStreamRec.toByteArray()));
        System.out.println("recovery_pub.txt: \n" + new String(CryptUtils.getPublicKeyString(keyPairRec).getBytes()));
    }
}

CryptUtils

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.RSAPrivateKey;
import org.bouncycastle.asn1.pkcs.RSAPublicKey;
import org.bouncycastle.asn1.sec.ECPrivateKey;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.jcajce.util.DefaultJcaJceHelper;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.openssl.*;
import org.bouncycastle.openssl.jcajce.*;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.operator.OutputEncryptor;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import org.bouncycastle.pkcs.jcajce.JcePKCSPBEInputDecryptorProviderBuilder;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.util.io.pem.PemWriter;
import sun.security.x509.X509CertImpl;

import javax.security.auth.x500.X500Principal;
import java.io.*;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 *
 */
public class CryptUtils {

    static{
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     *
     * @param privateKey
     * @param password
     * @param outputStream
     * @throws Exception
     */
    public static void writePkcs1(PrivateKey privateKey, String password, OutputStream outputStream) throws Exception {
        PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStream));
        final PEMEncryptor pemEncryptor = new JcePEMEncryptorBuilder("AES-256-CBC").build(password.toCharArray());
        JcaMiscPEMGenerator gen = new JcaMiscPEMGenerator(privateKey, pemEncryptor);
        PemObject obj = gen.generate();
        pemWriter.writeObject(obj);
        pemWriter.close();
    }

    /**
     *
     * @param privateKey
     * @param password
     * @param outputStream
     * @throws Exception
     */
    public static void writePkcs8(PrivateKey privateKey, String password, OutputStream outputStream) throws Exception {
        PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStream));
        JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(
                PKCS8Generator.PBE_SHA1_3DES);
        encryptorBuilder.setRandom(new SecureRandom());
        encryptorBuilder.setPasssword(password.toCharArray());
        OutputEncryptor oe = encryptorBuilder.build();
        JcaPKCS8Generator gen = new JcaPKCS8Generator(privateKey, oe);
        pemWriter.writeObject(gen.generate());
        pemWriter.close();
    }

    /**
     *
     * @param password
     * @param isPkcs8
     * @param outputStream
     * @return
     * @throws Exception
     */
    public static KeyPair generateEncryptedSmPrivateKey(String password, Boolean isPkcs8, OutputStream outputStream)
            throws Exception {
        ECNamedCurveParameterSpec ecNamedCurveParameterSpec = ECNamedCurveTable.getParameterSpec("sm2p256v1");
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
        keyPairGenerator.initialize(ecNamedCurveParameterSpec, new SecureRandom());
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        if (!isPkcs8) {
            writePkcs1(keyPair.getPrivate(), password, outputStream);
        } else {
            writePkcs8(keyPair.getPrivate(), password, outputStream);
        }
        return keyPair;
    }

    /**
     *
     * @param password
     * @param isPkcs8
     * @param outputStream
     * @return
     * @throws Exception
     */
    public static KeyPair generateEncryptedEcck1PrivateKey(String password, Boolean isPkcs8, OutputStream outputStream)
            throws Exception {
        ECNamedCurveParameterSpec ecParameterSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", "BC");
        keyPairGenerator.initialize(ecParameterSpec, new SecureRandom());
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        if (!isPkcs8) {
            writePkcs1(keyPair.getPrivate(), password, outputStream);
        } else {
            writePkcs8(keyPair.getPrivate(), password, outputStream);
        }
        return keyPair;
    }
    /**
     *
     * @param keyPair
     * @return
     * @throws Exception
     */
    public static String getPublicKeyString(KeyPair keyPair) throws Exception {
        ECPrivateKey ecPrivateKey = ECPrivateKey.getInstance(
                PrivateKeyInfo.getInstance(keyPair.getPrivate().getEncoded()).parsePrivateKey());
        byte[] originalBytes = ecPrivateKey.getPublicKey().getBytes();
        byte[] transform = new byte[originalBytes.length - 1];
        System.arraycopy(originalBytes, 1, transform, 0, transform.length);
        return Hex.toHexString(transform);
    }
}

此工具类需要依赖以下两个JAR包,在Mychain Java SDK中已进行了依赖,无需再单独做处理。

1