Java Code Examples for org.fisco.bcos.web3j.crypto.gm.GenCredential#create()

The following examples show how to use org.fisco.bcos.web3j.crypto.gm.GenCredential#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PublicKeyGmTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
@Test
public void checkPubCorrect() throws IOException {
     String defaultUserPrivateKey = "SzK9KCjpyVCW0T9K9r/MSlmcpkeckYKVn/D1X7fzzp18MM7yHhUHQugTxKXVJJY5XWOb4zZ79IXMBu77zmXsr0mCRnATZTUqFfWLX6tUBIw=";
     String defaultPub = "0xc5d877bff9923af55f248fb48b8907dc7d00cac3ba19b4259aebefe325510af7bd0a75e9a8e8234aa7aa58bc70510ee4bef02201a86006196da4e771c47b71b4";
     String defaultAddress = "0xf1585b8d0e08a0a00fff662e24d67ba95a438256";

    Credentials credential = GenCredential.create(defaultUserPrivateKey);
    System.out.println("private: ");
    System.out.println(credential.getEcKeyPair().getPrivateKey());
    System.out.println(Numeric.toHexStringNoPrefix(credential.getEcKeyPair().getPrivateKey()));
    System.out.println("pub: ");
    System.out.println(credential.getEcKeyPair().getPublicKey());
    System.out.println("address: ");
    System.out.println(credential.getAddress());
    System.out.println(Keys.getAddress(credential.getEcKeyPair().getPublicKey()));
}
 
Example 2
Source File: TestBase.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 3
Source File: AccountUtils.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public static Account newAccount(boolean flag)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException,
                NoSuchProviderException {
    // guomi
    Account account = new Account();
    if (flag) {
        EncryptType.encryptType = 1;
        account.setEncryptType("guomi");
    } else {
        EncryptType.encryptType = 0;
        account.setEncryptType("standard");
    }
    Credentials credentials = GenCredential.create();

    String address = credentials.getAddress();
    String privateKey = credentials.getEcKeyPair().getPrivateKey().toString(16);
    String publicKey = credentials.getEcKeyPair().getPublicKey().toString(16);

    account.setAddress(address);
    account.setPrivateKey(privateKey);
    account.setPublicKey(publicKey);
    return account;
}
 
Example 4
Source File: PermissionServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testNodeManger() throws Exception {
    address = "0x832f299af98c215f7ada010a966b12126483cd00";
    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    //生成web3sdk使用的Credentials
    Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));
    PermissionService permissionService = new PermissionService(web3j, credentialsPEM);

    // TablePermission
    System.out.println(permissionService.grantNodeManager(address));
    assertNotNull(permissionService.grantNodeManager(address));
    System.out.println(permissionService.listNodeManager().get(0).getAddress());
    assertTrue(permissionService.listNodeManager().size() != 0);
    System.out.println(permissionService.revokeNodeManager(address));
    assertNotNull(permissionService.revokeNodeManager(address));
}
 
Example 5
Source File: PerformanceDTTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public void initialize(String groupId) throws Exception {
    ApplicationContext context =
            new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.setGroupId(Integer.parseInt(groupId));
    service.run();

    ChannelEthereumService channelEthereumService = new ChannelEthereumService();
    channelEthereumService.setChannelService(service);

    Web3AsyncThreadPoolSize.web3AsyncCorePoolSize = 3000;
    Web3AsyncThreadPoolSize.web3AsyncPoolSize = 2000;

    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500);

    web3 =
            Web3j.build(
                    channelEthereumService,
                    15 * 100,
                    scheduledExecutorService,
                    Integer.parseInt(groupId));
    credentials = GenCredential.create();
    transactionManager = Contract.getTheTransactionManager(web3, credentials);
}
 
Example 6
Source File: PrecompiledSysConfigServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testSystemConfig() throws Exception {

    key = "tx_count_limit"; // key: tx_count_limit, tx_gas_limit
    value = "300000001";

    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    //链管理员私钥加载
    Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));

    SystemConfigService systemConfigService = new SystemConfigService(web3j, credentialsPEM);

    System.out.println(web3j.getSystemConfigByKey(key).send().getResult());
    System.out.println(systemConfigService.setValueByKey(key, value));
    assertNotNull(systemConfigService.setValueByKey(key, value));
    System.out.println(web3j.getSystemConfigByKey(key).send().getResult());
    assertNotNull(web3j.getSystemConfigByKey(key));
}
 
Example 7
Source File: TransactionEncoderTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void testGMSignMessage() {
    EncryptType encryptType = new EncryptType(1);

    Credentials credentials =
            GenCredential.create(
                    "a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6");
    System.out.println(credentials.getEcKeyPair().getPublicKey().toString(16));

    Credentials credentials1 =
            Credentials.create(
                    "a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6");
    System.out.println(credentials1.getEcKeyPair().getPublicKey().toString(16));

    byte[] signedMessage =
            TransactionEncoder.signMessage(createContractTransaction(), credentials);
    String hexMessage = Numeric.toHexString(signedMessage);
    assertThat(
            hexMessage,
            is(
                    "0xf8948201f4010a8201f5800a850000000000b8408234c544a9f3ce3b401a92cc7175602ce2a1e29b1ec135381c7d2a9e8f78f3edc9c06ee55252857c9a4560cb39e9d70d40f4331cace4d2b3121b967fa7a829f0a03d8627050f6688f27e2b5b89c9c141d3a48603029849e088486d1c7ea079ea7fa037024ed35d2c099d7eb68fb133e57735b03605ec32ded39ab305c3b56e5d99e7"));
}
 
Example 8
Source File: CnsServiceTest.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
@Test
    public void testRegCns() throws Exception {
        contractName = "Evidence1";
        version = "1.0";
        address = "0x8acf30e511c885163b8b9d85f34b806c216da6cc";
        abi = "{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"bytes32\"},{\"name\":\"decription\",\"type\":\"string\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"evidence\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]";
        contractNameAndVersion = "Evidencee:1.0";

        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        PEMManager pem = context.getBean(PEMManager.class);
        ECKeyPair pemKeyPair = pem.getECKeyPair();
        //链管理员私钥加载
        Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));

        CnsService cnsService = new CnsService(web3j, credentialsPEM);
//        System.out.println(cnsService.registerCns(contractName, version, address, abi));
//        assertNotNull(cnsService.registerCns(contractName, version, address, abi));

        // 默认获取最新版本
//        String res = cnsService.getAddressByContractNameAndVersion("contractNameAndVersion");
        List<CnsInfo> list = new ArrayList<>();
                list = cnsService.queryCnsByName(contractName);
        System.out.println(contractNameAndVersion);
//        System.out.println(cnsService.getAddressByContractNameAndVersion(contractName));
//        assertNotNull(cnsService.getAddressByContractNameAndVersion(contractName));
//        System.out.println(cnsService.queryCnsByName(contractName).size());
//        System.out.println(cnsService.queryCnsByName(contractName).get(0).getAddress());
//        System.out.println(cnsService.queryCnsByName(contractName).get(1).getAddress());
//        assertTrue(cnsService.queryCnsByName(contractName).size() != 0);

    }
 
Example 9
Source File: KeyStoreService.java    From WeBASE-Transaction with Apache License 2.0 5 votes vote down vote up
/**
 * get random Address.
 * 
 * @return
 */
public String getRandomAddress() throws BaseException {
    try {
        Credentials credentials = GenCredential.create();
        return credentials.getAddress();
    } catch (Exception e) {
        log.error("getRandomAddress fail.");
        throw new BaseException(ConstantCode.SYSTEM_ERROR);
    }
}
 
Example 10
Source File: GMTableTestClient.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
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]));
        service.run(); // run the daemon service
        // init the client keys
        keyPair = Keys.createEcKeyPair();
        credentials = GenCredential.create(keyPair.getPrivateKey().toString(16));

        logger.info("-----> start test !");
        logger.info("init AOMP ChannelEthereumService");
        ChannelEthereumService channelEthereumService = new ChannelEthereumService();
        channelEthereumService.setChannelService(service);
        channelEthereumService.setTimeout(5 * 1000);
        try {
            web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0]));
        } catch (Exception e) {
            System.out.println("\nPlease provide groupID in the first parameters");
            System.exit(0);
        }

        if (args.length > 1) {
            if ("deploy".equals(args[1])) {
                deployTableTest();
            } else {
                String[] params = new String[args.length - 1];
                for (int i = 0; i < params.length; i++) params[i] = args[i + 1];
                testTableTest(params);
            }
        } else {
            System.out.println(
                    "\nPlease choose follow commands:\n deploy, create, insert, select, update or remove");
        }
        System.exit(0);
    }
 
Example 11
Source File: KeyStoreService.java    From WeBASE-Transaction with Apache License 2.0 5 votes vote down vote up
/**
 * get user Address.
 * 
 * @return
 */
public String getAddress() throws BaseException {
    try {
        String privateKey = properties.getPrivateKey();
        Credentials credentials = GenCredential.create(privateKey);
        return credentials.getAddress();
    } catch (Exception e) {
        log.error("getAddress fail.");
        throw new BaseException(ConstantCode.SYSTEM_ERROR);
    }
}
 
Example 12
Source File: KeyStoreService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * get random credential to call transaction(not execute)
 * 2019/11/26 support guomi
 */
public Credentials getCredentialsForQuery() {
    log.debug("start getCredentialsForQuery. ");
    // create keyPair(support guomi)
    KeyStoreInfo keyStoreInfo;
    try {
        ECKeyPair keyPair = GenCredential.createKeyPair();
        keyStoreInfo = keyPair2KeyStoreInfo(keyPair, "");
    } catch (Exception e) {
        log.error("fail getCredentialsForQuery.", e);
        throw new FrontException("create random Credentials for query failed");
    }
    return GenCredential.create(keyStoreInfo.getPrivateKey());
}
 
Example 13
Source File: UserControllerTest.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateKey() throws Exception {
    // guomi use GenCredential
   Credentials credentials = GenCredential.create("3bed914595c159cbce70ec5fb6aff3d6797e0c5ee5a7a9224a21cae8932d84a4");
    System.out.println( credentials.getAddress());
    System.out.println( credentials.getEcKeyPair().getPrivateKey().toString(16));
    System.out.println(  credentials.getEcKeyPair().getPublicKey().toString(16));
}
 
Example 14
Source File: GMOkTransaction.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    EncryptType encryptType = new EncryptType(1);
    String groupId = "1";
    ApplicationContext context =
            new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.run();
    System.out.println("===================================================================");

    ChannelEthereumService channelEthereumService = new ChannelEthereumService();
    channelEthereumService.setChannelService(service);
    channelEthereumService.setTimeout(10000);
    Web3j web3 = Web3j.build(channelEthereumService, Integer.parseInt(groupId));
    BigInteger gasPrice = new BigInteger("300000000");
    BigInteger gasLimit = new BigInteger("3000000000");

    Credentials credentials1 =
            GenCredential.create(
                    "a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6");

    ContractGasProvider contractGasProvider = new StaticGasProvider(gasPrice, gasLimit);
    final Ok okDemo = Ok.deploy(web3, credentials1, contractGasProvider).send();

    for (int i = 0; i < 1; i++) {
        System.out.println("####contract address is: " + okDemo.getContractAddress());
        TransactionReceipt receipt = okDemo.trans(new BigInteger("4")).send();

        System.out.println(" balance = " + okDemo.get().send().intValue());
    }
    System.exit(0);
}
 
Example 15
Source File: SendGMTxTest.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
@Test
public void testSystemConfigService() throws Exception {
    Credentials credentials2 =
            GenCredential.create("a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6");

    // web3j
    SystemConfigService systemConfigSerivce = new SystemConfigService(web3ApiService.getWeb3j(1), credentials2);
    systemConfigSerivce.setValueByKey("tx_count_limit", "2000");
    String value = web3ApiService.getWeb3j(1).getSystemConfigByKey("tx_count_limit").send().getSystemConfigByKey();
    System.out.println(value);
    assertTrue("2000".equals(value));
}
 
Example 16
Source File: TransactionEncoderTest.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
@Test
public void testGMSignMessage() {


        Credentials credentials =
                GenCredential.create(
                        "a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f");

        Instant startTime = Instant.now();

        byte[] signedMessage = TransactionEncoder.signMessage(createContractTransaction(), credentials);
        System.out.println("       sign  useTime: " + Duration.between(startTime, Instant.now()).toMillis());
     //   String hexMessage = Numeric.toHexString(signedMessage);


        // gm createTransaction!
        EncryptType encryptType = new EncryptType(1);
         assertSame(encryptType.getEncryptType(),1);
        Credentials gmcredentials =
                GenCredential.create(
                        "a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f");

        Instant startTime1 = Instant.now();
         TransactionEncoder.signMessage(createContractTransaction(), gmcredentials);
        System.out.println(" guomi sign  useTime: " + Duration.between(startTime1, Instant.now()).toMillis());
  //      String hexMessage1 = Numeric.toHexString(signedMessage1);
}
 
Example 17
Source File: PerformanceDTTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public void initialize(String groupId) throws Exception {

        ApplicationContext context =
                new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Service service = context.getBean(Service.class);
        service.setGroupId(Integer.parseInt(groupId));
        service.run();

        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();

        dagTransfer =
                DagTransfer.load(
                        dagTransferAddr,
                        web3,
                        credentials,
                        new StaticGasProvider(
                                new BigInteger("30000000"), new BigInteger("30000000")));
        transactionManager = Contract.getTheTransactionManager(web3, credentials);
    }
 
Example 18
Source File: CoreBeanConfig.java    From WeBASE-Collect-Bee with Apache License 2.0 4 votes vote down vote up
@Bean
public static Credentials getCredentials() {
    return GenCredential.create();
}
 
Example 19
Source File: KeyStoreService.java    From WeBASE-Sign with Apache License 2.0 4 votes vote down vote up
@Cacheable(cacheNames = "getPrivatekey")
public  Credentials getCredentioan(String privateKey) {
    return   GenCredential.create(privateKey);
}
 
Example 20
Source File: PerformanceDTTest.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}