use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.
the class LedgerAdminDatasetTest method testSerialization.
@Test
public void testSerialization() {
String keyPrefix = "";
LedgerInitData initSetting = new LedgerInitData();
ConsensusParticipantData[] parties = new ConsensusParticipantData[5];
BlockchainKeypair[] bckeys = new BlockchainKeypair[parties.length];
for (int i = 0; i < parties.length; i++) {
bckeys[i] = BlockchainKeyGenerator.getInstance().generate();
parties[i] = new ConsensusParticipantData();
parties[i].setId(i);
parties[i].setAddress(AddressEncoding.generateAddress(bckeys[i].getPubKey()));
parties[i].setHostAddress(new NetworkAddress("192.168.10." + (10 + i), 10010 + 10 * i));
parties[i].setName("Participant[" + i + "]");
parties[i].setPubKey(bckeys[i].getPubKey());
parties[i].setParticipantState(ParticipantNodeState.CONSENSUS);
}
ConsensusParticipantData[] parties1 = Arrays.copyOf(parties, 4);
initSetting.setConsensusParticipants(parties1);
byte[] csSysSettingBytes = new byte[64];
rand.nextBytes(csSysSettingBytes);
initSetting.setConsensusSettings(new Bytes(csSysSettingBytes));
initSetting.setConsensusProvider("consensus-provider");
CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length];
for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) {
supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]);
}
CryptoConfig cryptoSetting = new CryptoConfig();
cryptoSetting.setSupportedProviders(supportedProviders);
cryptoSetting.setAutoVerifyHash(true);
cryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256);
initSetting.setCryptoSetting(cryptoSetting);
initSetting.setIdentityMode(IdentityMode.KEYPAIR);
byte[] ledgerSeed = new byte[16];
rand.nextBytes(ledgerSeed);
initSetting.setLedgerSeed(ledgerSeed);
MemoryKVStorage testStorage = new MemoryKVStorage();
// Create intance with init setting;
LedgerAdminDataSetEditor ledgerAdminDataset = new LedgerAdminDataSetEditor(initSetting, keyPrefix, testStorage, testStorage);
ledgerAdminDataset.getRolePrivileges().addRolePrivilege("DEFAULT", new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.REGISTER_USER, LedgerPermission.APPROVE_TX }, new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, TransactionPermission.CONTRACT_OPERATION });
ledgerAdminDataset.getAuthorizations().addUserRoles(parties[0].getAddress(), RolesPolicy.UNION, "DEFAULT");
// New created instance is updated until being committed;
assertTrue(ledgerAdminDataset.isUpdated());
// Hash of account is null until being committed;
assertNull(ledgerAdminDataset.getHash());
LedgerMetadata_V2 meta = ledgerAdminDataset.getMetadata();
assertNull(meta.getParticipantsHash());
// Commit, and check the storage keys;
ledgerAdminDataset.commit();
// New created instance isn't updated after being committed;
assertFalse(ledgerAdminDataset.isUpdated());
// Hash of account isn't null after being committed;
assertNotNull(ledgerAdminDataset.getHash());
meta = ledgerAdminDataset.getMetadata();
assertNotNull(meta.getParticipantsHash());
assertNotNull(meta.getSettingsHash());
assertNotNull(meta.getRolePrivilegesHash());
assertNotNull(meta.getUserRolesHash());
assertNotNull(ledgerAdminDataset.getRolePrivileges().getRolePrivilege("DEFAULT"));
// ----------------------
// Reload account from storage with readonly mode, and check the integrity of
// data;
HashDigest adminAccHash = ledgerAdminDataset.getHash();
LedgerAdminDataSetEditor reloadAdminAccount1 = new LedgerAdminDataSetEditor(-1, adminAccHash, keyPrefix, testStorage, testStorage, LedgerDataStructure.MERKLE_TREE, true);
LedgerMetadata_V2 meta2 = reloadAdminAccount1.getMetadata();
assertNotNull(meta2.getParticipantsHash());
assertNotNull(meta2.getSettingsHash());
assertNotNull(meta2.getRolePrivilegesHash());
assertNotNull(meta2.getUserRolesHash());
// verify realod settings of admin account;
verifyRealoadingSettings(reloadAdminAccount1, adminAccHash, ledgerAdminDataset.getMetadata(), ledgerAdminDataset.getSettings());
// verify the consensus participant list;
verifyRealoadingParities(reloadAdminAccount1, parties1);
// It will throw exeception because of this account is readonly;
verifyReadonlyState(reloadAdminAccount1);
verifyRealoadingRoleAuthorizations(reloadAdminAccount1, ledgerAdminDataset.getRolePrivileges(), ledgerAdminDataset.getAuthorizations());
// --------------
// 重新加载,并进行修改;
LedgerAdminDataSetEditor reloadAdminAccount2 = new LedgerAdminDataSetEditor(-1, adminAccHash, keyPrefix, testStorage, testStorage, LedgerDataStructure.MERKLE_TREE, false);
LedgerConfiguration newSetting = new LedgerConfiguration(reloadAdminAccount2.getPreviousSetting());
byte[] newCsSettingBytes = new byte[64];
rand.nextBytes(newCsSettingBytes);
newSetting.setConsensusSetting(new Bytes(newCsSettingBytes));
newSetting.getCryptoSetting().setAutoVerifyHash(false);
reloadAdminAccount2.setLedgerSetting(newSetting);
reloadAdminAccount2.addParticipant(parties[4]);
reloadAdminAccount2.getRolePrivileges().addRolePrivilege("ADMIN", new LedgerPermission[] { LedgerPermission.APPROVE_TX }, new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION });
reloadAdminAccount2.getRolePrivileges().disablePermissions("DEFAULT", TransactionPermission.CONTRACT_OPERATION);
reloadAdminAccount2.getAuthorizations().addUserRoles(parties[1].getAddress(), RolesPolicy.UNION, "DEFAULT", "ADMIN");
reloadAdminAccount2.commit();
LedgerSettings newlyLedgerSettings = reloadAdminAccount2.getSettings();
// record the new account hash;
HashDigest newAccHash = reloadAdminAccount2.getHash();
LedgerMetadata_V2 newMeta = reloadAdminAccount2.getMetadata();
// load the last version of account and verify again;
LedgerAdminDataSetEditor previousAdminAccount = new LedgerAdminDataSetEditor(-1, adminAccHash, keyPrefix, testStorage, testStorage, LedgerDataStructure.MERKLE_TREE, true);
verifyRealoadingSettings(previousAdminAccount, adminAccHash, ledgerAdminDataset.getMetadata(), ledgerAdminDataset.getSettings());
verifyRealoadingParities(previousAdminAccount, parties1);
verifyReadonlyState(previousAdminAccount);
// load the hash of new committing;
LedgerAdminDataSetEditor newlyAdminAccount = new LedgerAdminDataSetEditor(-1, newAccHash, keyPrefix, testStorage, testStorage, LedgerDataStructure.MERKLE_TREE, true);
verifyRealoadingSettings(newlyAdminAccount, newAccHash, newMeta, newlyLedgerSettings);
verifyRealoadingParities(newlyAdminAccount, parties);
verifyReadonlyState(newlyAdminAccount);
// System.out.println("========= [LedgerAdminAccount Test] Show generated storage keys... =======");
// testStorage.printStoragedKeys();
}
use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.
the class LedgerEditorTest method testRollback.
@Test
public void testRollback() {
BlockchainKeypair parti0 = LedgerTestUtils.createKeyPair("7VeRLBwqTAz8oRazEazeaEfqei46sk2FzvBgyHMUBJvrUEGT", "7VeRUm27GbrsX9HbQSZguChLp24HZYub6s5FJ7FjBht8BmbA");
BlockchainKeypair parti1 = LedgerTestUtils.createKeyPair("7VeRNJasZp76ThmUkoAajJEduotS4JC6T9wzhz9TDPvjLCRk", "7VeRcBcPkTZ4hFwfcKRgFJWdDesHyysQWkKYC6xfPApbfvwQ");
BlockchainKeypair parti2 = LedgerTestUtils.createKeyPair("7VeR7uSd7sqxkMp73936MoK7eUSmGPVrsmrwdekiR9fmvdYN", "7VeRUkgMXRegHHWhezv4LdJV6oQuSXo6Ezp2sjC2M5NTUWkz");
BlockchainKeypair parti3 = LedgerTestUtils.createKeyPair("7VeR8X8fa9th42XSXvnuBLfR4v3dxjXq6jPfvF7nDPB2MTo1", "7VeRdreAev1E8ySsLWX7rRMArh5wHBTmZXKwNUuoVo7cBn6o");
BlockchainKeypair[] participants = new BlockchainKeypair[] { parti0, parti1, parti2, parti3 };
final MemoryKVStorage STORAGE = new MemoryKVStorage();
// 初始化账本到指定的存储库;
HashDigest ledgerHash = LedgerTestUtils.initLedger(STORAGE, parti0, parti1, parti2, parti3);
System.out.printf("\r\n------------ LEDGER [%s] -----------\r\n", ledgerHash.toBase58());
// 验证重新加载的正确性;
LedgerManager manager = new LedgerManager();
LedgerRepository repo = manager.register(ledgerHash, STORAGE, LedgerDataStructure.MERKLE_TREE);
LedgerBlock block = repo.getBlock(ledgerHash);
assertNotNull(block);
assertNotNull(block.getHash());
assertEquals(0, block.getHeight());
// 创建交易连续交易,验证中间的交易回滚是否影响前后的交易;
BlockchainKeypair user1 = LedgerTestUtils.createKeyPair("7VeRKf3GFLFcBfzvtzmtyMXEoX2HYGEJ4j7CmHcnRV99W5Dp", "7VeRYQjeAaQY5Po8MMtmGNHA2SniqLXmJaZwBS5K8zTtMAU1");
TransactionRequest req1 = LedgerTestUtils.createTxRequest_UserReg_SHA256(user1, ledgerHash, 1580315317127L, parti0, parti0);
// 引发错误的参数:ts=1580315317127;
// txhash=j5wPGKT5CUzwi8j6VfCWaP2p9YZ6WVWtMANp9HbHWzvhgG
System.out.printf("\r\n ===||=== transactionRequest1.getTransactionContent().getHash()=[%s]\r\n", req1.getTransactionHash().toBase58());
BlockchainKeypair user2 = LedgerTestUtils.createKeyPair("7VeRKSnDFveTfLLMsLZDmmhGmgf7i142XHgBFjnrKuS95tY3", "7VeRTiJ2TpQD9aBi29ajnqdntgoVBANmC3oCbHThKb5tzfTJ");
TransactionRequest req2 = LedgerTestUtils.createTxRequest_MultiOPs_WithNotExistedDataAccount_SHA256(user2, ledgerHash, 202001202020L, parti0, parti0);
System.out.printf("\r\n ===||=== transactionRequest2.getTransactionContent().getHash()=[%s]\r\n", req2.getTransactionHash().toBase58());
BlockchainKeypair user3 = LedgerTestUtils.createKeyPair("7VeRDoaSexqLWKkaZyrQwdwSuE9n5nszduMrYBfYRfEkREQV", "7VeRdFtTuLfrzCYJzQ6enQUkGTc83ATgjr8WbmfjBQuTFpHt");
TransactionRequest req3 = LedgerTestUtils.createTxRequest_UserReg_SHA256(user3, ledgerHash, 202001202020L, parti0, parti0);
System.out.printf("\r\n ===||=== transactionRequest3.getTransactionContent().getHash()=[%s]\r\n", req3.getTransactionHash().toBase58());
System.out.println("\r\n--------------- Start new Block 1 --------------\r\n");
// 创建交易;
LedgerEditor editor = repo.createNextBlock();
System.out.println("\r\n--------------- Start new tx1 --------------\r\n");
LedgerTransactionContext txctx1 = editor.newTransaction(req1);
((UserAccountSetEditor) (txctx1.getDataset().getUserAccountSet())).register(user1.getAddress(), user1.getPubKey());
TransactionResult tx1 = txctx1.commit(TransactionState.SUCCESS);
HashDigest txHash1 = tx1.getTransactionHash();
System.out.println("\r\n--------------- Start new tx2 --------------\r\n");
LedgerTransactionContext txctx2 = editor.newTransaction(req2);
((UserAccountSetEditor) (txctx2.getDataset().getUserAccountSet())).register(user2.getAddress(), user2.getPubKey());
TransactionResult tx2 = txctx2.discardAndCommit(TransactionState.DATA_ACCOUNT_DOES_NOT_EXIST);
HashDigest txHash2 = tx2.getTransactionHash();
System.out.println("\r\n--------------- Start new tx3 --------------\r\n");
LedgerTransactionContext txctx3 = editor.newTransaction(req3);
((UserAccountSetEditor) (txctx3.getDataset().getUserAccountSet())).register(user3.getAddress(), user3.getPubKey());
TransactionResult tx3 = txctx3.commit(TransactionState.SUCCESS);
HashDigest txHash3 = tx3.getTransactionHash();
System.out.println("\r\n--------------- Start preparing new block 1 --------------\r\n");
LedgerBlock block1 = editor.prepare();
System.out.println("\r\n--------------- Start commiting new block 1 --------------\r\n");
editor.commit();
System.out.printf("\r\n--------------- End commiting new block 1 [Storage.Count=%s]--------------\r\n\r\n", STORAGE.getStorageCount());
assertEquals(1, block1.getHeight());
// 重新加载和验证;
manager = new LedgerManager();
repo = manager.register(ledgerHash, STORAGE, LedgerDataStructure.MERKLE_TREE);
LedgerTransaction act_tx1 = repo.getTransactionSet().getTransaction(txHash1);
LedgerTransaction act_tx2 = repo.getTransactionSet().getTransaction(txHash2);
LedgerTransaction act_tx3 = repo.getTransactionSet().getTransaction(txHash3);
assertNotNull(act_tx3);
assertNotNull(act_tx2);
assertNotNull(act_tx1);
}
use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.
the class LedgerTransactionDataTest method initTransactionContent.
private TransactionContent initTransactionContent() throws Exception {
TxContentBlob contentBlob = null;
BlockchainKeypair id = BlockchainKeyGenerator.getInstance().generate(ClassicAlgorithm.ED25519);
HashDigest ledgerHash = Crypto.getHashFunction("SHA256").hash(UUID.randomUUID().toString().getBytes("UTF-8"));
BlockchainOperationFactory opFactory = new BlockchainOperationFactory();
contentBlob = new TxContentBlob(ledgerHash);
// contentBlob.setSubjectAccount(id.getAddress());
// contentBlob.setSequenceNumber(1);
DataAccountKVSetOperation kvsetOP = opFactory.dataAccount(id.getAddress()).setText("Name", "AAA", -1).getOperation();
contentBlob.addOperation(kvsetOP);
return contentBlob;
}
use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.
the class BlockFullRollBackTest method testBlockFullkRollBack.
@Test
public void testBlockFullkRollBack() {
final MemoryKVStorage STORAGE = new MemoryKVStorage();
final MemoryKVStorage STORAGE_Mock = Mockito.spy(STORAGE);
// 初始化账本到指定的存储库;
ledgerHash = initLedger(STORAGE_Mock, parti0, parti1, parti2, parti3);
System.out.println("---------- Ledger init OK !!! ----------");
// 加载账本;
LedgerManager ledgerManager = new LedgerManager();
LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE_Mock, LedgerDataStructure.MERKLE_TREE);
// 构造存储错误,并产生区块回滚
doThrow(BlockRollbackException.class).when(STORAGE_Mock).set(any(), any(), anyLong());
LedgerEditor newBlockEditor = ledgerRepo.createNextBlock();
OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration();
LedgerSecurityManager securityManager = getSecurityManager();
TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, ledgerRepo, opReg);
// 注册新用户;
BlockchainKeypair userKeypair = BlockchainKeyGenerator.getInstance().generate();
TransactionRequest transactionRequest = LedgerTestUtils.createTxRequest_UserReg(userKeypair, ledgerHash, parti0, parti0);
TransactionResponse txResp = txbatchProcessor.schedule(transactionRequest);
LedgerBlock newBlock = newBlockEditor.prepare();
try {
newBlockEditor.commit();
} catch (BlockRollbackException e) {
newBlockEditor.cancel();
}
// 验证正确性;
ledgerManager = new LedgerManager();
ledgerRepo = ledgerManager.register(ledgerHash, STORAGE_Mock, LedgerDataStructure.MERKLE_TREE);
LedgerBlock latestBlock = ledgerRepo.getLatestBlock();
assertEquals(ledgerRepo.getBlockHash(0), latestBlock.getHash());
assertEquals(0, latestBlock.getHeight());
LedgerDataSet ledgerDS = ledgerRepo.getLedgerDataSet(latestBlock);
boolean existUser = ledgerDS.getUserAccountSet().contains(userKeypair.getAddress());
assertFalse(existUser);
doCallRealMethod().when(STORAGE_Mock).set(any(), any(), anyLong());
// 区块正常提交
// 生成新区块;
LedgerEditor newBlockEditor1 = ledgerRepo.createNextBlock();
OperationHandleRegisteration opReg1 = new DefaultOperationHandleRegisteration();
LedgerSecurityManager securityManager1 = getSecurityManager();
TransactionBatchProcessor txbatchProcessor1 = new TransactionBatchProcessor(securityManager1, newBlockEditor1, ledgerRepo, opReg1);
// 注册新用户;
BlockchainKeypair userKeypair1 = BlockchainKeyGenerator.getInstance().generate();
TransactionRequest transactionRequest1 = LedgerTestUtils.createTxRequest_UserReg(userKeypair1, ledgerHash, parti0, parti0);
TransactionResponse txResp1 = txbatchProcessor1.schedule(transactionRequest1);
LedgerBlock newBlock1 = newBlockEditor1.prepare();
try {
newBlockEditor1.commit();
} catch (BlockRollbackException e) {
newBlockEditor1.cancel();
}
ledgerManager = new LedgerManager();
ledgerRepo = ledgerManager.register(ledgerHash, STORAGE_Mock, LedgerDataStructure.MERKLE_TREE);
LedgerBlock latestBlock1 = ledgerRepo.getLatestBlock();
assertEquals(newBlock1.getHash(), latestBlock1.getHash());
assertEquals(1, latestBlock1.getHeight());
LedgerDataSet ledgerDS1 = ledgerRepo.getLedgerDataSet(latestBlock1);
boolean existUser1 = ledgerDS1.getUserAccountSet().contains(userKeypair1.getAddress());
assertTrue(existUser1);
}
use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.
the class ProxyClientTest method peerStart.
public void peerStart(BftsmartNodeServer[] nodeServers) {
BftsmartNodeSettings[] nodesSettings = new BftsmartNodeSettings[nodeNum];
for (int i = 0; i < nodeNum; i++) {
BlockchainKeypair keyPair = BlockchainKeyGenerator.getInstance().generate();
PubKey pubKey = keyPair.getPubKey();
NetworkAddress peerNodeServ = new NetworkAddress("127.0.0.1", peerStartPort + i * 10);
NodeSettings node = new BftsmartNodeConfig(pubKey, i, peerNodeServ);
nodesSettings[i] = (BftsmartNodeSettings) node;
}
BftsmartConsensusConfig consensusConfig = new BftsmartConsensusConfig(nodesSettings, PropertiesUtils.getOrderedValues(bftsmartConf), 0);
for (int j = 0; j < nodeNum; j++) {
BftsmartServerSettingConfig serverSettings = new BftsmartServerSettingConfig();
serverSettings.setReplicaSettings(nodesSettings[j]);
serverSettings.setConsensusSettings(consensusConfig);
BftsmartNodeServer server = new BftsmartNodeServer(serverSettings, null, null, new MemoryStorage("test"));
nodeServers[j] = server;
nodeStartPools.execute(() -> {
server.start();
startPeer.countDown();
});
}
}
Aggregations