Search in sources :

Example 11 with ChannelEthereumService

use of org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService in project web3sdk by FISCO-BCOS.

the class TestBase method setUpBeforeClass.

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.run();
    ChannelEthereumService channelEthereumService = new ChannelEthereumService();
    channelEthereumService.setChannelService(service);
    System.out.println("EncryptType =>  " + EncryptType.getEncryptType());
    web3j = Web3j.build(channelEthereumService, service.getGroupId());
    credentials = GenCredential.create();
    Ok ok = Ok.deploy(web3j, credentials, new StaticGasProvider(gasPrice, gasLimit)).send();
    blockNumber = ok.getTransactionReceipt().get().getBlockNumber();
    blockHash = ok.getTransactionReceipt().get().getBlockHash();
    txHash = ok.getTransactionReceipt().get().getTransactionHash();
}
Also used : StaticGasProvider(org.fisco.bcos.web3j.tx.gas.StaticGasProvider) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) Service(org.fisco.bcos.channel.client.Service) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) Ok(org.fisco.bcos.channel.test.guomi.Ok) BeforeClass(org.junit.BeforeClass)

Example 12 with ChannelEthereumService

use of org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService in project web3sdk by FISCO-BCOS.

the class TransactionResourceTest method main.

public static void main(String[] args) throws Exception {
    // init the Service
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.setGroupId(Integer.parseInt(args[0]));
    // run the daemon service
    service.run();
    // init the client keys
    keyPair = Keys.createEcKeyPair();
    credentials = Credentials.create(keyPair);
    logger.info("-----> start TransactionResourceTest !");
    ChannelEthereumService channelEthereumService = new ChannelEthereumService();
    channelEthereumService.setChannelService(service);
    try {
        web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0]));
    } catch (Exception e) {
        System.out.println("Please provide groupID in the first paramters");
        System.exit(1);
    }
    try {
        if (args.length == 4) {
            BigInteger blockNumber = new BigInteger(args[2]);
            BigInteger transactionIndex = new BigInteger(args[3]);
            DefaultBlockParameter defaultBlockParameter = DefaultBlockParameter.valueOf(blockNumber);
            BcosTransaction bcosTransaction = web3j.getTransactionByBlockNumberAndIndex(defaultBlockParameter, transactionIndex).send();
            String transactionHash = bcosTransaction.getTransaction().get().getHash();
            BcosBlock block = web3j.getBlockByNumber(defaultBlockParameter, true).send();
            String transactionsRootHash = block.getBlock().getTransactionsRoot();
            System.out.println("transactionsRoot: " + transactionsRootHash);
            String receiptRootHash = block.getBlock().getReceiptsRoot();
            System.out.println("receiptRootHash : " + receiptRootHash);
            TransactionResource transactionResource = new TransactionResource(web3j);
            if ("getTrans".equals(args[1])) {
                TransactionWithProof transactionWithProof = web3j.getTransactionByHashWithProof(transactionHash).send();
                if (transactionWithProof == null) {
                    System.out.println("transactionWithProof == null");
                    System.exit(1);
                }
                System.out.println("***********Test getTransactionByHashWithProof************");
                List<MerkleProofUnit> transactionProof = transactionWithProof.getTransactionWithProof().getTxProof();
                System.out.println("transactionProof:" + transactionProof);
                TransactionWithProof newTransactionWithProof = transactionResource.getTransactionWithProof(transactionHash, transactionsRootHash);
                if (newTransactionWithProof == null) {
                    System.out.println("Test getTransactionByHashWithProof failed!");
                } else {
                    System.out.println(newTransactionWithProof.getTransactionWithProof().toString());
                    System.out.println("Test getTransactionByHashWithProof successfully!");
                }
            } else if ("getReceipt".equals(args[1])) {
                TransactionReceiptWithProof transactionReceiptWithProof = web3j.getTransactionReceiptByHashWithProof(transactionHash).send();
                if (transactionReceiptWithProof == null) {
                    System.out.println("transactionReceiptWithProof == null");
                    System.exit(1);
                }
                List<MerkleProofUnit> transactionReceiptProof = transactionReceiptWithProof.getTransactionReceiptWithProof().getReceiptProof();
                System.out.println("receiptProof:" + transactionReceiptProof);
                System.out.println("***********Test getReceiptByHashWithProof************");
                TransactionReceiptWithProof newTransactionReceiptWithProof = transactionResource.getTransactionReceiptWithProof(transactionHash, receiptRootHash);
                if (newTransactionReceiptWithProof == null) {
                    System.out.println("Test getReceiptByHashWithProof failed!");
                } else {
                    System.out.println(newTransactionReceiptWithProof.getTransactionReceiptWithProof().toString());
                    System.out.println("Test getReceiptByHashWithProof successfully!");
                }
            } else if ("getAll".equals(args[1])) {
                System.out.println("***********Test getTransactionAndReceiptWithProof************");
                ImmutablePair<TransactionWithProof, TransactionReceiptWithProof> pair = transactionResource.getTransactionAndReceiptWithProof(transactionHash, transactionsRootHash, receiptRootHash);
                if (pair == null) {
                    System.out.println("Test getAll failed!");
                } else {
                    System.out.println("Test getAll successful!");
                }
            } else {
                System.out.println("Command not found!");
            }
        } else {
            System.out.println("Please choose follow commands:\n getTrans or getReceipt!");
        }
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
        System.exit(1);
    }
    System.exit(0);
}
Also used : BcosTransaction(org.fisco.bcos.web3j.protocol.core.methods.response.BcosTransaction) TransactionReceiptWithProof(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceiptWithProof) TransactionWithProof(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionWithProof) MerkleProofUnit(org.fisco.bcos.web3j.protocol.core.methods.response.MerkleProofUnit) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) DefaultBlockParameter(org.fisco.bcos.web3j.protocol.core.DefaultBlockParameter) ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) BcosBlock(org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock) BigInteger(java.math.BigInteger) List(java.util.List)

Example 13 with ChannelEthereumService

use of org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService in project web3sdk by FISCO-BCOS.

the class ConnectionCallback method queryBlockNumber.

private void queryBlockNumber(ChannelHandlerContext ctx) throws JsonProcessingException {
    final String host = ChannelHandlerContextHelper.getPeerHost(ctx);
    String seq = channelService.newSeq();
    BcosMessage bcosMessage = new BcosMessage();
    bcosMessage.setType((short) ChannelMessageType.CHANNEL_RPC_REQUEST.getType());
    bcosMessage.setSeq(seq);
    ChannelEthereumService channelEthereumService = new ChannelEthereumService();
    channelEthereumService.setChannelService(channelService);
    Request<Integer, BlockNumber> request = new Request<>("getBlockNumber", Arrays.asList(channelService.getGroupId()), channelEthereumService, BlockNumber.class);
    bcosMessage.setData(ObjectMapperFactory.getObjectMapper().writeValueAsBytes(request));
    ByteBuf byteBuf = ctx.alloc().buffer();
    bcosMessage.writeHeader(byteBuf);
    bcosMessage.writeExtra(byteBuf);
    String content = new String(bcosMessage.getData());
    logger.info(" query block number host: {}, seq: {}, content: {}", host, seq, content);
    channelService.getSeq2Callback().put(seq, new BcosResponseCallback() {

        @Override
        public void onResponse(BcosResponse response) {
            try {
                BlockNumber blockNumber = ObjectMapperFactory.getObjectMapper().readValue(response.getContent(), BlockNumber.class);
                SocketChannel socketChannel = (SocketChannel) ctx.channel();
                InetSocketAddress socketAddress = socketChannel.remoteAddress();
                channelService.getNodeToBlockNumberMap().put(socketAddress.getAddress().getHostAddress() + socketAddress.getPort(), blockNumber.getBlockNumber());
                logger.info(" query blocknumer, host:{}, blockNumber: {} ", host, blockNumber.getBlockNumber());
            } catch (Exception e) {
                logger.error(" query blocknumer failed, host: {}, message: {} ", host, e.getMessage());
                throw new MessageDecodingException(response.getContent());
            }
        }
    });
    ctx.writeAndFlush(byteBuf);
}
Also used : BcosResponseCallback(org.fisco.bcos.channel.client.BcosResponseCallback) SocketChannel(io.netty.channel.socket.SocketChannel) BcosResponse(org.fisco.bcos.channel.dto.BcosResponse) InetSocketAddress(java.net.InetSocketAddress) Request(org.fisco.bcos.web3j.protocol.core.Request) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) ByteBuf(io.netty.buffer.ByteBuf) MessageDecodingException(org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) BigInteger(java.math.BigInteger) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) MessageDecodingException(org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException) BlockNumber(org.fisco.bcos.web3j.protocol.core.methods.response.BlockNumber)

Example 14 with ChannelEthereumService

use of org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService in project web3sdk by FISCO-BCOS.

the class PerfomanceTableRemove 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 _id = getNextID();
                        Random r = new Random();
                        long l1 = r.nextLong();
                        tabletest.remove("fruit" + l1 % TableTestClient.modevalue, BigInteger.valueOf(_id), callback);
                    } 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) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Credentials(org.fisco.bcos.web3j.crypto.Credentials)

Example 15 with ChannelEthereumService

use of org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService in project web3sdk by FISCO-BCOS.

the class PerformanceOkD 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...");
        OkD ok = OkD.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;
        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();
                    PerformanceOkCallback callback = new PerformanceOkCallback();
                    callback.setCollector(collector);
                    try {
                        ok.trans(String.valueOf(random.nextLong()), new BigInteger("1"), callback);
                    } 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) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Credentials(org.fisco.bcos.web3j.crypto.Credentials)

Aggregations

ChannelEthereumService (org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService)27 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)25 ApplicationContext (org.springframework.context.ApplicationContext)24 Service (org.fisco.bcos.channel.client.Service)23 Web3j (org.fisco.bcos.web3j.protocol.Web3j)17 BigInteger (java.math.BigInteger)15 Credentials (org.fisco.bcos.web3j.crypto.Credentials)12 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)11 TransactionReceipt (org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt)10 RateLimiter (com.google.common.util.concurrent.RateLimiter)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 ThreadPoolTaskExecutor (org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)9 Random (java.util.Random)6 StaticGasProvider (org.fisco.bcos.web3j.tx.gas.StaticGasProvider)5 TransactionException (org.fisco.bcos.web3j.protocol.exceptions.TransactionException)4 SecureRandom (java.security.SecureRandom)2 ECKeyPair (org.fisco.bcos.web3j.crypto.ECKeyPair)2 EncryptType (org.fisco.bcos.web3j.crypto.EncryptType)2 DefaultBlockParameter (org.fisco.bcos.web3j.protocol.core.DefaultBlockParameter)2 ContractGasProvider (org.fisco.bcos.web3j.tx.gas.ContractGasProvider)2