Search in sources :

Example 6 with Credentials

use of org.fisco.bcos.web3j.crypto.Credentials in project web3sdk by FISCO-BCOS.

the class PerfomanceTableQuery method main.

public static void main(String[] args) throws Exception {
    try {
        String groupId = args[3];
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Service service = context.getBean(Service.class);
        service.setGroupId(Integer.parseInt(groupId));
        service.run();
        System.out.println("Start test...");
        System.out.println("===================================================================");
        ChannelEthereumService channelEthereumService = new ChannelEthereumService();
        channelEthereumService.setChannelService(service);
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500);
        Web3j web3 = Web3j.build(channelEthereumService, 15 * 100, scheduledExecutorService, Integer.parseInt(groupId));
        Credentials credentials = Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6");
        BigInteger gasPrice = new BigInteger("30000000");
        BigInteger gasLimit = new BigInteger("30000000");
        String command = args[0];
        Integer count = 0;
        Integer qps = 0;
        switch(command) {
            case "trans":
                count = Integer.parseInt(args[1]);
                qps = Integer.parseInt(args[2]);
                break;
            default:
                System.out.println("Args: <trans> <Total> <QPS>");
        }
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(200);
        threadPool.setMaxPoolSize(500);
        threadPool.setQueueCapacity(count);
        threadPool.initialize();
        System.out.println("Deploying contract...");
        TableTest tabletest = TableTest.deploy(web3, credentials, gasPrice, gasLimit).send();
        PerfomanceCollector collector = new PerfomanceCollector();
        collector.setTotal(count);
        RateLimiter limiter = RateLimiter.create(qps);
        Integer area = count / 10;
        final Integer total = count;
        Random random = new Random(System.currentTimeMillis());
        System.out.println("Start test,total:" + count);
        for (Integer i = 0; i < count; ++i) {
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    limiter.acquire();
                    PerfomanceTableTestCallback callback = new PerfomanceTableTestCallback();
                    callback.setCollector(collector);
                    try {
                        Long time_before = System.currentTimeMillis();
                        long _id = getNextID();
                        Random r = new Random();
                        long l1 = r.nextLong();
                        Tuple3<List<byte[]>, List<BigInteger>, List<byte[]>> lists = tabletest.select("fruit" + l1 % TableTestClient.modevalue).send();
                        Long time_after = System.currentTimeMillis();
                        TransactionReceipt receipt = new TransactionReceipt();
                        receipt.setStatus("0");
                        collector.onSelectMessage(receipt, time_after - time_before);
                    /*
                                    List<byte[]> value1 = lists.getValue1();
                                          List<BigInteger> value2 = lists.getValue2();
                                          List<byte[]> value3 = lists.getValue3();
                                          logger.info("record numbers = " + value1.size());
                                          System.out.println("record numbers = " + value1.size());
                                          for (int i = 0; i < value1.size(); i++) {
                                            String name = new String(value1.get(i));
                                            logger.info("name = " + name);
                                            System.out.println("name = " + name);
                                            int item_id = value2.get(i).intValue();
                                            logger.info("item_id = " + item_id);
                                            System.out.println("item_id = " + item_id);
                                            String item_name = new String(value3.get(i));
                                            logger.info("item_name = " + item_name);
                                            System.out.println("item_name = " + item_name);
                                          }

                                          */
                    } catch (Exception e) {
                        TransactionReceipt receipt = new TransactionReceipt();
                        receipt.setStatus("-1");
                        callback.onResponse(receipt);
                        logger.error("Error sending:", e);
                    }
                    int current = sended.incrementAndGet();
                    if (current >= area && ((current % area) == 0)) {
                        System.out.println("Already sended: " + current + "/" + total + " transactions");
                    }
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Service(org.fisco.bcos.channel.client.Service) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Web3j(org.fisco.bcos.web3j.protocol.Web3j) Random(java.util.Random) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Tuple3(org.fisco.bcos.web3j.tuples.generated.Tuple3) AtomicLong(java.util.concurrent.atomic.AtomicLong) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Credentials(org.fisco.bcos.web3j.crypto.Credentials)

Example 7 with Credentials

use of org.fisco.bcos.web3j.crypto.Credentials in project web3sdk by FISCO-BCOS.

the class PerformanceEvidenceVerify method main.

public static void main(String[] args) throws Exception {
    try {
        String groupId = args[3];
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Service service = context.getBean(Service.class);
        service.setGroupId(Integer.parseInt(groupId));
        service.run();
        System.out.println("Start Evidence test...");
        System.out.println("===================================================================");
        ChannelEthereumService channelEthereumService = new ChannelEthereumService();
        channelEthereumService.setChannelService(service);
        Web3AsyncThreadPoolSize.web3AsyncCorePoolSize = 3000;
        Web3AsyncThreadPoolSize.web3AsyncPoolSize = 2000;
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500);
        Web3j web3 = Web3j.build(channelEthereumService, 15 * 100, scheduledExecutorService, Integer.parseInt(groupId));
        Credentials credentials = GenCredential.create();
        BigInteger gasPrice = new BigInteger("30000000");
        BigInteger gasLimit = new BigInteger("30000000");
        String command = args[0];
        Integer count = 0;
        Integer qps = 0;
        switch(command) {
            case "insert":
                count = Integer.parseInt(args[1]);
                qps = Integer.parseInt(args[2]);
                break;
            default:
                System.out.println("Args: <insert> <Total> <QPS>");
        }
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(200);
        threadPool.setMaxPoolSize(500);
        threadPool.setQueueCapacity(count);
        threadPool.initialize();
        System.out.println("Deploying Evidence contract...");
        EvidenceVerify evidence = EvidenceVerify.deploy(web3, credentials, gasPrice, gasLimit).send();
        PerformanceCollector collector = new PerformanceCollector();
        collector.setTotal(count);
        RateLimiter limiter = RateLimiter.create(qps);
        Integer area = count / 10;
        final Integer total = count;
        ECDSASign signHandler = new ECDSASign();
        ECKeyPair keyPair = Keys.createEcKeyPair();
        System.out.println("Start test,total:" + count);
        System.out.println("address:" + credentials.getAddress());
        String signAddr = Keys.getAddress(keyPair);
        System.out.println("standardCredential address:" + signAddr);
        for (Integer i = 0; i < count; ++i) {
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    limiter.acquire();
                    PerformanceOkCallback callback = new PerformanceOkCallback();
                    callback.setCollector(collector);
                    try {
                        String evi = "test";
                        String evInfo = "test_info";
                        int random = new SecureRandom().nextInt(50000);
                        String eviId = String.valueOf(random);
                        // sign to evi
                        byte[] message = Hash.sha3(evi.getBytes());
                        Sign.SignatureData sign = signHandler.signMessage(evi.getBytes(), keyPair);
                        int v = sign.getV();
                        evidence.insertEvidence(evi, evInfo, eviId, signAddr, message, BigInteger.valueOf(v), sign.getR(), sign.getS(), callback);
                    } catch (Exception e) {
                        TransactionReceipt receipt = new TransactionReceipt();
                        receipt.setStatus("-1");
                        callback.onResponse(receipt);
                        logger.info(e.getMessage());
                    }
                    int current = sended.incrementAndGet();
                    if (current >= area && ((current % area) == 0)) {
                        System.out.println("Already sended: " + current + "/" + total + " transactions");
                    }
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ECKeyPair(org.fisco.bcos.web3j.crypto.ECKeyPair) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Service(org.fisco.bcos.channel.client.Service) SecureRandom(java.security.SecureRandom) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Web3j(org.fisco.bcos.web3j.protocol.Web3j) ECDSASign(org.fisco.bcos.web3j.crypto.ECDSASign) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Credentials(org.fisco.bcos.web3j.crypto.Credentials)

Example 8 with Credentials

use of org.fisco.bcos.web3j.crypto.Credentials in project web3sdk by FISCO-BCOS.

the class PerformanceDTTest method userTransferSignTxPerfTest.

/**
 * Stress tests that create tx and sign them
 *
 * @param totalSignedTxCount
 * @param threadC
 * @throws InterruptedException
 */
public void userTransferSignTxPerfTest(BigInteger totalSignedTxCount, int threadC) throws InterruptedException {
    ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
    threadPool.setCorePoolSize(threadC > 0 ? threadC : 10);
    threadPool.setMaxPoolSize(threadC > 0 ? threadC : 10);
    threadPool.setQueueCapacity(threadC > 0 ? threadC : 10);
    threadPool.initialize();
    Credentials credentials = GenCredential.create();
    TransferSignTransactionManager extendedRawTransactionManager = new TransferSignTransactionManager(null, credentials, BigInteger.ONE, BigInteger.ONE);
    dagTransfer = DagTransfer.load(dagTransferAddr, null, extendedRawTransactionManager, new StaticGasProvider(new BigInteger("30000000"), new BigInteger("30000000")));
    AtomicLong signed = new AtomicLong(0);
    long startTime = System.currentTimeMillis();
    System.out.println(" => " + dateFormat.format(new Date()));
    for (int i = 0; i < threadC; i++) {
        threadPool.execute(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    long index = signed.incrementAndGet();
                    if (index > totalSignedTxCount.intValue()) {
                        break;
                    }
                    DagTransferUser from = dagUserMgr.getFrom((int) index);
                    DagTransferUser to = dagUserMgr.getTo((int) index);
                    Random random = new Random();
                    int r = random.nextInt(100) + 1;
                    BigInteger amount = BigInteger.valueOf(r);
                    try {
                        String signedTransaction = dagTransfer.userTransferSeq(from.getUser(), to.getUser(), amount);
                        if (index % (totalSignedTxCount.longValue() / 10) == 0) {
                            System.out.println("Signed transaction: " + String.valueOf(index * 100 / totalSignedTxCount.longValue()) + "%");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.exit(-1);
                    }
                }
            }
        });
    }
    while (signed.get() < totalSignedTxCount.intValue()) {
        Thread.sleep(10);
    }
    long endTime = System.currentTimeMillis();
    double elapsed = (endTime - startTime) / 1000.0;
    System.out.println(" => " + dateFormat.format(new Date()));
    System.out.print(" sign transactions finished, elapse time: " + elapsed + ", tx count = " + totalSignedTxCount + " ,sps = " + (totalSignedTxCount.intValue() / elapsed));
    System.exit(0);
}
Also used : StaticGasProvider(org.fisco.bcos.web3j.tx.gas.StaticGasProvider) Date(java.util.Date) AtomicLong(java.util.concurrent.atomic.AtomicLong) Random(java.util.Random) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Credentials(org.fisco.bcos.web3j.crypto.Credentials)

Example 9 with Credentials

use of org.fisco.bcos.web3j.crypto.Credentials in project web3sdk by FISCO-BCOS.

the class AccountTest method accountTest.

@Test
public void accountTest() throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext-keystore-sample.xml");
    // test p12
    P12Manager p12 = context.getBean(P12Manager.class);
    ECKeyPair p12KeyPair = p12.getECKeyPair();
    assertEquals(p12KeyPair.getPrivateKey().toString(16), PRIVATE_KEY);
    assertEquals(p12KeyPair.getPublicKey().toString(16), PUBLIC_KEY);
    ECPublicKey publicKey = (ECPublicKey) p12.getPublicKey();
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue = new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));
    assertEquals(publicKeyValue.toString(16), PUBLIC_KEY);
    Credentials credentials = Credentials.create(p12KeyPair);
    assertEquals(credentials.getAddress(), ADDRESS);
    // test pem
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    assertEquals(pemKeyPair.getPrivateKey().toString(16), PRIVATE_KEY);
    assertEquals(pemKeyPair.getPublicKey().toString(16), PUBLIC_KEY);
    Credentials credentialsPEM = Credentials.create(pemKeyPair);
    assertEquals(credentialsPEM.getAddress(), ADDRESS);
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ECPublicKey(org.bouncycastle.jce.interfaces.ECPublicKey) PEMManager(org.fisco.bcos.channel.client.PEMManager) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) P12Manager(org.fisco.bcos.channel.client.P12Manager) ECKeyPair(org.fisco.bcos.web3j.crypto.ECKeyPair) BigInteger(java.math.BigInteger) Credentials(org.fisco.bcos.web3j.crypto.Credentials) Test(org.junit.Test)

Example 10 with Credentials

use of org.fisco.bcos.web3j.crypto.Credentials in project web3sdk by FISCO-BCOS.

the class SolidityFunctionWrapper method buildDeployMethods.

List<MethodSpec> buildDeployMethods(String className, TypeSpec.Builder classBuilder, List<AbiDefinition> functionDefinitions) {
    boolean constructor = false;
    List<MethodSpec> methodSpecs = new ArrayList<>();
    for (AbiDefinition functionDefinition : functionDefinitions) {
        if (functionDefinition.getType().equals("constructor")) {
            constructor = true;
            methodSpecs.add(buildDeploy(className, functionDefinition, Credentials.class, CREDENTIALS, true));
            methodSpecs.add(buildDeploy(className, functionDefinition, TransactionManager.class, TRANSACTION_MANAGER, true));
            methodSpecs.add(buildDeploy(className, functionDefinition, Credentials.class, CREDENTIALS, false));
            methodSpecs.add(buildDeploy(className, functionDefinition, TransactionManager.class, TRANSACTION_MANAGER, false));
        }
    }
    // constructor will not be specified in ABI file if its empty
    if (!constructor) {
        MethodSpec.Builder credentialsMethodBuilder = getDeployMethodSpec(className, Credentials.class, CREDENTIALS, true);
        methodSpecs.add(buildDeployNoParams(credentialsMethodBuilder, className, CREDENTIALS, true));
        MethodSpec.Builder credentialsMethodBuilderNoGasProvider = getDeployMethodSpec(className, Credentials.class, CREDENTIALS, false);
        methodSpecs.add(buildDeployNoParams(credentialsMethodBuilderNoGasProvider, className, CREDENTIALS, false));
        MethodSpec.Builder transactionManagerMethodBuilder = getDeployMethodSpec(className, TransactionManager.class, TRANSACTION_MANAGER, true);
        methodSpecs.add(buildDeployNoParams(transactionManagerMethodBuilder, className, TRANSACTION_MANAGER, true));
        MethodSpec.Builder transactionManagerMethodBuilderNoGasProvider = getDeployMethodSpec(className, TransactionManager.class, TRANSACTION_MANAGER, false);
        methodSpecs.add(buildDeployNoParams(transactionManagerMethodBuilderNoGasProvider, className, TRANSACTION_MANAGER, false));
    }
    return methodSpecs;
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) AbiDefinition(org.fisco.bcos.web3j.protocol.core.methods.response.AbiDefinition) TransactionManager(org.fisco.bcos.web3j.tx.TransactionManager) ArrayList(java.util.ArrayList) Credentials(org.fisco.bcos.web3j.crypto.Credentials)

Aggregations

Credentials (org.fisco.bcos.web3j.crypto.Credentials)20 BigInteger (java.math.BigInteger)14 ApplicationContext (org.springframework.context.ApplicationContext)13 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)13 Service (org.fisco.bcos.channel.client.Service)12 Web3j (org.fisco.bcos.web3j.protocol.Web3j)12 ChannelEthereumService (org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService)12 TransactionReceipt (org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt)10 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)9 ThreadPoolTaskExecutor (org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)9 RateLimiter (com.google.common.util.concurrent.RateLimiter)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 Random (java.util.Random)7 ECKeyPair (org.fisco.bcos.web3j.crypto.ECKeyPair)6 StaticGasProvider (org.fisco.bcos.web3j.tx.gas.StaticGasProvider)5 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 EncryptType (org.fisco.bcos.web3j.crypto.EncryptType)2 AbiDefinition (org.fisco.bcos.web3j.protocol.core.methods.response.AbiDefinition)2 TransactionManager (org.fisco.bcos.web3j.tx.TransactionManager)2 ContractGasProvider (org.fisco.bcos.web3j.tx.gas.ContractGasProvider)2