Search in sources :

Example 6 with TxBuilder

use of com.jd.blockchain.transaction.TxBuilder in project jdchain-core by blockchain-jd-com.

the class ManagementController method prepareUpdateTx.

// 在指定的账本上准备一笔激活参与方状态及系统配置参数的操作
private TransactionRequest prepareUpdateTx(HashDigest ledgerHash, ParticipantNode node, NetworkAddress updateConsensusNodeAddress, Properties customProperties) {
    int activeID = node.getId();
    // organize system config properties
    Property[] properties = ParticipantContext.context().participantService().createUpdateProperties(updateConsensusNodeAddress, node.getPubKey(), activeID, customProperties);
    TxBuilder txbuilder = new TxBuilder(ledgerHash, ledgerCryptoSettings.get(ledgerHash).getHashAlgorithm());
    // This transaction contains participant state update and settings update two
    // ops
    txbuilder.states().update(new BlockchainIdentityData(node.getPubKey()), ParticipantNodeState.CONSENSUS);
    txbuilder.consensus().update(properties);
    TransactionRequestBuilder reqBuilder = txbuilder.prepareRequest();
    reqBuilder.signAsEndpoint(new AsymmetricKeypair(ledgerKeypairs.get(ledgerHash).getPubKey(), ledgerKeypairs.get(ledgerHash).getPrivKey()));
    return reqBuilder.buildRequest();
}
Also used : TxBuilder(com.jd.blockchain.transaction.TxBuilder) Property(utils.Property) ServiceEndpoint(com.jd.httpservice.agent.ServiceEndpoint)

Example 7 with TxBuilder

use of com.jd.blockchain.transaction.TxBuilder in project jdchain-core by blockchain-jd-com.

the class LedgerInitializer method buildGenesisTransaction.

/**
 * 根据初始化配置,生成创始交易;
 * <p>
 *
 * “创世交易”按顺序由以下操作组成:<br>
 * (1) 账本初始化 {@link LedgerInitOperation}:此操作仅用于锚定了原始的交易配置,对应的
 * {@link OperationHandle} 执行空操作,由“创世交易”其余的操作来表达对账本的实际修改;<br>
 * (2) 注册用户 {@link UserRegisterOperation}:有一项或者多项;<br>
 * (3) 配置角色 {@link RolesConfigureOperation}:有一项或者多项;<br>
 * (4) 授权用户 {@link UserAuthorizeOperation}:有一项或者多项;<br>
 *
 * @param initSetting
 * @param securityInitSettings
 * @return
 */
public static TransactionContent buildGenesisTransaction(LedgerInitSetting initSetting, SecurityInitSettings securityInitSettings) {
    // 账本初始化交易的账本 hash 为 null;
    TransactionBuilder initTxBuilder = new TxBuilder(null, initSetting.getCryptoSetting().getHashAlgorithm());
    // 定义账本初始化操作;
    initTxBuilder.ledgers().create(initSetting);
    // 注册用户
    for (GenesisUser u : initSetting.getGenesisUsers()) {
        if (initSetting.getIdentityMode() == IdentityMode.CA) {
            X509Certificate cert = CertificateUtils.parseCertificate(u.getCertificate());
            initTxBuilder.users().register(cert);
        } else {
            initTxBuilder.users().register(new BlockchainIdentityData(u.getPubKey()));
        }
    }
    // 配置角色;
    for (RoleInitSettings roleSettings : securityInitSettings.getRoles()) {
        initTxBuilder.security().roles().configure(roleSettings.getRoleName()).enable(roleSettings.getLedgerPermissions()).enable(roleSettings.getTransactionPermissions());
    }
    // 授权用户;
    for (UserAuthInitSettings userAuthSettings : securityInitSettings.getUserAuthorizations()) {
        initTxBuilder.security().authorziations().forUser(userAuthSettings.getUserAddress()).authorize(userAuthSettings.getRoles()).setPolicy(userAuthSettings.getPolicy());
    }
    // 账本初始化配置声明的创建时间来初始化交易时间戳;注:不能用本地时间,因为共识节点之间的本地时间系统不一致;
    return initTxBuilder.prepareContent(initSetting.getCreatedTime());
}
Also used : RoleInitSettings(com.jd.blockchain.ledger.RoleInitSettings) TransactionBuilder(com.jd.blockchain.ledger.TransactionBuilder) UserAuthInitSettings(com.jd.blockchain.ledger.UserAuthInitSettings) TxBuilder(com.jd.blockchain.transaction.TxBuilder) BlockchainIdentityData(com.jd.blockchain.ledger.BlockchainIdentityData) X509Certificate(java.security.cert.X509Certificate) GenesisUser(com.jd.blockchain.ledger.GenesisUser)

Example 8 with TxBuilder

use of com.jd.blockchain.transaction.TxBuilder in project jdchain-core by blockchain-jd-com.

the class ContractInvokingTest method buildBlock.

private LedgerBlock buildBlock(LedgerRepository ledgerRepo, LedgerService ledgerService, OperationHandleRegisteration opReg, TxDefinitor txDefinitor) {
    LedgerBlock preBlock = ledgerRepo.getLatestBlock();
    LedgerDataSet previousBlockDataset = ledgerRepo.getLedgerDataSet(preBlock);
    LedgerEditor newBlockEditor = ledgerRepo.createNextBlock();
    TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(getSecurityManager(), newBlockEditor, ledgerRepo, opReg);
    CryptoSetting cryptoSetting = ledgerRepo.getAdminInfo().getSettings().getCryptoSetting();
    TxBuilder txBuilder = new TxBuilder(ledgerRepo.getHash(), cryptoSetting.getHashAlgorithm());
    txDefinitor.buildTx(txBuilder);
    TransactionRequest txReq = buildAndSignRequest(txBuilder, parti0, parti0);
    TransactionResponse resp = txbatchProcessor.schedule(txReq);
    // 提交区块;
    TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare();
    txResultHandle.commit();
    LedgerBlock latestBlock = ledgerRepo.getLatestBlock();
    assertNotNull(resp.getBlockHash());
    assertEquals(preBlock.getHeight() + 1, resp.getBlockHeight());
    return latestBlock;
}
Also used : TransactionBatchProcessor(com.jd.blockchain.ledger.core.TransactionBatchProcessor) LedgerEditor(com.jd.blockchain.ledger.core.LedgerEditor) TransactionBatchResultHandle(com.jd.blockchain.service.TransactionBatchResultHandle) TxBuilder(com.jd.blockchain.transaction.TxBuilder) LedgerDataSet(com.jd.blockchain.ledger.core.LedgerDataSet)

Example 9 with TxBuilder

use of com.jd.blockchain.transaction.TxBuilder in project jdchain-core by blockchain-jd-com.

the class ContractInvokingTest method testRollbackWhileVersionConfliction.

/**
 * 验证在合约方法中写入数据账户时,如果版本校验失败是否会引发异常而导致回滚;<br>
 * 期待正确的表现是引发异常而回滚当前交易;
 */
@Ignore("需要更新合约")
@Test
public void testRollbackWhileVersionConfliction() {
    // 初始化账本到指定的存储库;
    HashDigest ledgerHash = initLedger(storage, parti0, parti1, parti2, parti3);
    // 重新加载账本;
    LedgerManager ledgerManager = new LedgerManager();
    LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, storage, LedgerDataStructure.MERKLE_TREE);
    // 创建合约处理器;
    ContractInvokingHandle contractInvokingHandle = new ContractInvokingHandle();
    // 创建和加载合约实例;
    BlockchainKeypair contractKey = BlockchainKeyGenerator.getInstance().generate();
    Bytes contractAddress = contractKey.getAddress();
    TxTestContractImpl contractInstance = new TxTestContractImpl();
    contractInvokingHandle.setup(contractAddress, TxTestContract.class, contractInstance);
    // 注册合约处理器;
    DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration();
    opReg.registerHandle(contractInvokingHandle);
    // 发布指定地址合约
    deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey);
    // 注册数据账户;
    BlockchainKeypair kpDataAccount = BlockchainKeyGenerator.getInstance().generate();
    contractInstance.setDataAddress(kpDataAccount.getAddress());
    registerDataAccount(ledgerRepo, ledgerManager, opReg, ledgerHash, kpDataAccount);
    // 调用合约
    // 构建基于接口调用合约的交易请求,用于测试合约调用;
    buildBlock(ledgerRepo, ledgerManager, opReg, new TxDefinitor() {

        @Override
        public void buildTx(TxBuilder txBuilder) {
            TxTestContract contractProxy = txBuilder.contract(contractAddress, TxTestContract.class);
            contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K1", "V1-0", -1);
            contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K2", "V2-0", -1);
        }
    });
    // 预期数据都能够正常写入;
    DataEntry<String, TypedValue> kv1 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K1", 0);
    DataEntry<String, TypedValue> kv2 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K2", 0);
    assertEquals(0, kv1.getVersion());
    assertEquals(0, kv2.getVersion());
    assertEquals("V1-0", kv1.getValue().stringValue());
    assertEquals("V2-0", kv2.getValue().stringValue());
    // 构建基于接口调用合约的交易请求,用于测试合约调用;
    buildBlock(ledgerRepo, ledgerManager, opReg, new TxDefinitor() {

        @Override
        public void buildTx(TxBuilder txBuilder) {
            TxTestContract contractProxy = txBuilder.contract(contractAddress, TxTestContract.class);
            contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K1", "V1-1", 0);
            contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K2", "V2-1", 0);
        }
    });
    // 预期数据都能够正常写入;
    kv1 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K1", 1);
    kv2 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K2", 1);
    assertEquals(1, kv1.getVersion());
    assertEquals(1, kv2.getVersion());
    assertEquals("V1-1", kv1.getValue().stringValue());
    assertEquals("V2-1", kv2.getValue().stringValue());
    // 构建基于接口调用合约的交易请求,用于测试合约调用;
    buildBlock(ledgerRepo, ledgerManager, opReg, new TxDefinitor() {

        @Override
        public void buildTx(TxBuilder txBuilder) {
            TxTestContract contractProxy = txBuilder.contract(contractAddress, TxTestContract.class);
            contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K1", "V1-2", 1);
            contractProxy.testRollbackWhileVersionConfliction(kpDataAccount.getAddress().toBase58(), "K2", "V2-2", // 预期会回滚;
            0);
        }
    });
    // 预期数据回滚,账本没有发生变更;
    kv1 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K1", 1);
    assertEquals(1, kv1.getVersion());
    assertEquals("V1-1", kv1.getValue().stringValue());
    kv1 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K1", 2);
    assertNull(kv1);
    kv2 = ledgerRepo.getDataAccountSet().getAccount(kpDataAccount.getAddress()).getDataset().getDataEntry("K2", 1);
    assertEquals(1, kv2.getVersion());
}
Also used : LedgerManager(com.jd.blockchain.ledger.core.LedgerManager) DefaultOperationHandleRegisteration(com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration) TxBuilder(com.jd.blockchain.transaction.TxBuilder) Matchers.anyString(org.mockito.Matchers.anyString) LedgerRepository(com.jd.blockchain.ledger.core.LedgerRepository) TxTestContract(test.com.jd.blockchain.ledger.TxTestContract) Bytes(utils.Bytes) HashDigest(com.jd.blockchain.crypto.HashDigest) TxTestContractImpl(test.com.jd.blockchain.ledger.TxTestContractImpl) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 10 with TxBuilder

use of com.jd.blockchain.transaction.TxBuilder in project jdchain-core by blockchain-jd-com.

the class ContractInvokingTest method testNormal.

@Ignore("合约需要更新")
@Test
public void testNormal() {
    // 初始化账本到指定的存储库;
    HashDigest ledgerHash = initLedger(storage, parti0, parti1, parti2, parti3);
    // 重新加载账本;
    LedgerManager ledgerManager = new LedgerManager();
    LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, storage, LedgerDataStructure.MERKLE_TREE);
    // 创建合约处理器;
    ContractInvokingHandle contractInvokingHandle = new ContractInvokingHandle();
    // 创建和加载合约实例;
    BlockchainKeypair contractKey = BlockchainKeyGenerator.getInstance().generate();
    Bytes contractAddress = contractKey.getAddress();
    TestContract contractInstance = Mockito.mock(TestContract.class);
    final String asset = "AK";
    final long issueAmount = new Random().nextLong();
    when(contractInstance.issue(anyString(), anyLong())).thenReturn(issueAmount);
    // 装载合约;
    contractInvokingHandle.setup(contractAddress, TestContract.class, contractInstance);
    // 注册合约处理器;
    DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration();
    opReg.registerHandle(contractInvokingHandle);
    // 发布指定地址合约
    deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey);
    // 创建新区块的交易处理器;
    LedgerBlock preBlock = ledgerRepo.getLatestBlock();
    LedgerDataSet previousBlockDataset = ledgerRepo.getLedgerDataSet(preBlock);
    // 加载合约
    LedgerEditor newBlockEditor = ledgerRepo.createNextBlock();
    LedgerSecurityManager securityManager = getSecurityManager();
    TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, ledgerRepo, opReg);
    // 构建基于接口调用合约的交易请求,用于测试合约调用;
    CryptoSetting cryptoSetting = ledgerRepo.getAdminInfo().getSettings().getCryptoSetting();
    TxBuilder txBuilder = new TxBuilder(ledgerHash, cryptoSetting.getHashAlgorithm());
    TestContract contractProxy = txBuilder.contract(contractAddress, TestContract.class);
    // 构造调用合约的交易;
    contractProxy.issue(asset, issueAmount);
    TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest();
    txReqBuilder.signAsEndpoint(parti0);
    txReqBuilder.signAsNode(parti0);
    TransactionRequest txReq = txReqBuilder.buildRequest();
    TransactionResponse resp = txbatchProcessor.schedule(txReq);
    verify(contractInstance, times(1)).issue(asset, issueAmount);
    OperationResult[] opResults = resp.getOperationResults();
    assertEquals(1, opResults.length);
    assertEquals(0, opResults[0].getIndex());
    byte[] expectedRetnBytes = BinaryProtocol.encode(TypedValue.fromInt64(issueAmount), BytesValue.class);
    byte[] reallyRetnBytes = BinaryProtocol.encode(opResults[0].getResult(), BytesValue.class);
    assertArrayEquals(expectedRetnBytes, reallyRetnBytes);
    // 提交区块;
    TransactionBatchResultHandle txResultHandle = txbatchProcessor.prepare();
    txResultHandle.commit();
    LedgerBlock latestBlock = ledgerRepo.getLatestBlock();
    assertEquals(preBlock.getHeight() + 1, latestBlock.getHeight());
    assertEquals(resp.getBlockHeight(), latestBlock.getHeight());
    assertEquals(resp.getBlockHash(), latestBlock.getHash());
    // 再验证一次结果;
    assertEquals(1, opResults.length);
    assertEquals(0, opResults[0].getIndex());
    reallyRetnBytes = BinaryProtocol.encode(opResults[0].getResult(), BytesValue.class);
    assertArrayEquals(expectedRetnBytes, reallyRetnBytes);
}
Also used : LedgerManager(com.jd.blockchain.ledger.core.LedgerManager) TransactionBatchProcessor(com.jd.blockchain.ledger.core.TransactionBatchProcessor) Matchers.anyString(org.mockito.Matchers.anyString) LedgerRepository(com.jd.blockchain.ledger.core.LedgerRepository) Bytes(utils.Bytes) HashDigest(com.jd.blockchain.crypto.HashDigest) Random(java.util.Random) DefaultOperationHandleRegisteration(com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration) LedgerSecurityManager(com.jd.blockchain.ledger.core.LedgerSecurityManager) LedgerEditor(com.jd.blockchain.ledger.core.LedgerEditor) TxBuilder(com.jd.blockchain.transaction.TxBuilder) LedgerDataSet(com.jd.blockchain.ledger.core.LedgerDataSet) TxTestContract(test.com.jd.blockchain.ledger.TxTestContract) TransactionBatchResultHandle(com.jd.blockchain.service.TransactionBatchResultHandle) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

TxBuilder (com.jd.blockchain.transaction.TxBuilder)18 LedgerEditor (com.jd.blockchain.ledger.core.LedgerEditor)6 HashDigest (com.jd.blockchain.crypto.HashDigest)5 LedgerDataSet (com.jd.blockchain.ledger.core.LedgerDataSet)5 TransactionBatchProcessor (com.jd.blockchain.ledger.core.TransactionBatchProcessor)5 TransactionBatchResultHandle (com.jd.blockchain.service.TransactionBatchResultHandle)5 LedgerManager (com.jd.blockchain.ledger.core.LedgerManager)4 LedgerRepository (com.jd.blockchain.ledger.core.LedgerRepository)4 DefaultOperationHandleRegisteration (com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration)3 ServiceEndpoint (com.jd.httpservice.agent.ServiceEndpoint)3 Test (org.junit.Test)3 Matchers.anyString (org.mockito.Matchers.anyString)3 TxTestContract (test.com.jd.blockchain.ledger.TxTestContract)3 Bytes (utils.Bytes)3 Property (utils.Property)3 LedgerSecurityManager (com.jd.blockchain.ledger.core.LedgerSecurityManager)2 Ignore (org.junit.Ignore)2 TxTestContractImpl (test.com.jd.blockchain.ledger.TxTestContractImpl)2 BlockchainIdentityData (com.jd.blockchain.ledger.BlockchainIdentityData)1 BlockchainKeypair (com.jd.blockchain.ledger.BlockchainKeypair)1