org.fisco.bcos.web3j.utils.Numeric Java Examples

The following examples show how to use org.fisco.bcos.web3j.utils.Numeric. 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: RawTransaction.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
protected RawTransaction(
        BigInteger randomid,
        BigInteger gasPrice,
        BigInteger gasLimit,
        BigInteger blockLimit,
        String to,
        BigInteger value,
        String data) {
    this.randomid = randomid;
    this.gasPrice = gasPrice;
    this.gasLimit = gasLimit;
    this.blockLimit = blockLimit;

    this.to = to;

    this.value = value;

    if (data != null) {
        this.data = Numeric.cleanHexPrefix(data);
    }
}
 
Example #2
Source File: ImportCertTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
     * address到底需不需要传入pub的开头的两位04
     * 答案: 不需要,公钥是128位的
     */
    @Test
    public void testAddress() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
        ECKeyPair key = Keys.createEcKeyPair();
        // 用byte[]穿进去获取公钥,就会可能多出一位0
        byte[] pubBytes = key.getPublicKey().toByteArray();
        System.out.println("=============原生的==============");
        System.out.println(key.getPublicKey()); //64bytes BigInteger
        System.out.println(Keys.getAddress(key.getPublicKey()));

        System.out.println("===========通过转成hex后获取地址============");
        System.out.println(Numeric.toHexStringNoPrefix(key.getPublicKey())); //Hex后显示
        System.out.println(Keys.getAddress(Numeric.toHexStringNoPrefix(key.getPublicKey())));

        System.out.println("===========通过byte[]============");
        System.out.println(Numeric.toHexStringNoPrefix(pubBytes)); // BigInteget=> byte[] => hex 多一位
        System.out.println(Keys.getAddress(Numeric.toHexStringNoPrefix(pubBytes)));
        System.out.println("===============");
//        System.out.println(Keys.getAddress(pubBytes));
    }
 
Example #3
Source File: CommonUtils.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * signatureDataToString. 19/12/24 support guomi: add byte[] pub in signatureData
 * 
 * @param signatureData signatureData
 */
public static String signatureDataToString(SignatureData signatureData) {
    byte[] byteArr;
    if (EncryptType.encryptType == 1) {
        byteArr = new byte[1 + signatureData.getR().length + signatureData.getS().length
                + PUBLIC_KEY_LENGTH_64];
        byteArr[0] = signatureData.getV();
        System.arraycopy(signatureData.getR(), 0, byteArr, 1, signatureData.getR().length);
        System.arraycopy(signatureData.getS(), 0, byteArr, signatureData.getR().length + 1,
                signatureData.getS().length);
        System.arraycopy(signatureData.getPub(), 0, byteArr,
                signatureData.getS().length + signatureData.getR().length + 1,
                signatureData.getPub().length);
    } else {
        byteArr = new byte[1 + signatureData.getR().length + signatureData.getS().length];
        byteArr[0] = signatureData.getV();
        System.arraycopy(signatureData.getR(), 0, byteArr, 1, signatureData.getR().length);
        System.arraycopy(signatureData.getS(), 0, byteArr, signatureData.getR().length + 1,
                signatureData.getS().length);
    }
    return Numeric.toHexString(byteArr, 0, byteArr.length, false);
}
 
Example #4
Source File: UserService.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * import pem file to import privateKey
 * @param reqImportPem
 * @return userId
 */
public Integer importPem(ReqImportPem reqImportPem) {
    PEMManager pemManager = new PEMManager();
    String privateKey;
    try {
        String pemContent = reqImportPem.getPemContent();
        pemManager.load(new ByteArrayInputStream(pemContent.getBytes()));
        privateKey = Numeric.toHexStringNoPrefix(pemManager.getECKeyPair().getPrivateKey());
    }catch (Exception e) {
        log.error("importKeyStoreFromPem error:[]", e);
        throw new NodeMgrException(ConstantCode.PEM_CONTENT_ERROR);
    }
    // pem's privateKey encoded here
    String privateKeyEncoded = NodeMgrTools.encodedBase64Str(privateKey);

    // store local and save in sign
    Integer userId = addUserInfo(reqImportPem.getGroupId(), reqImportPem.getUserName(),
            reqImportPem.getDescription(), reqImportPem.getUserType(), privateKeyEncoded);
    return userId;
}
 
Example #5
Source File: ImportCertTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
@Test
public void testPubAddress() throws IOException, CertificateException, IllegalAccessException, InstantiationException {
    /**
     * @param: nodeCert
     * 只有节点证书才是ECC椭圆曲线,获取pub的方法和区块链的一致
     * 其余的agency chain 的crt都是rsa方法,使用大素数方法计算,不一样
     */
    // need crt file
    InputStream node = new ClassPathResource("node.crt").getInputStream();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate nodeCert = (X509Certificate) cf.generateCertificate(node);
    // rsa算法的公钥和ecc的不一样
    ECPublicKeyImpl pub = (ECPublicKeyImpl) nodeCert.getPublicKey();
    byte[] pubBytes = pub.getEncodedPublicValue();
    String publicKey = Numeric.toHexStringNoPrefix(pubBytes);
    String address = Keys.getAddress(publicKey);
    byte[] addByteArray = Keys.getAddress(pubBytes);
    System.out.println("byte[] : pub ");
    System.out.println(pubBytes);
    System.out.println("====================================");
    System.out.println(publicKey); // 04e5e7efc9e8d5bed699313d5a0cd5b024b3c11811d50473b987b9429c2f6379742c88249a7a8ea64ab0e6f2b69fb8bb280454f28471e38621bea8f38be45bc42d
    System.out.println("byte[] to pub to address ");
    System.out.println(address); // f7b2c352e9a872d37a427601c162671202416dbc
    System.out.println("包含开头的04");
    System.out.println(byteToHex(addByteArray));
}
 
Example #6
Source File: SignTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testGmSignVerify() throws IOException {
    byte[] sourceData =
            Hex.decode("434477813974bf58f94bcf760833c2b40f77a5fc360485b0b9ed1bd9682edb45");
    String publicKey =
            "e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
    String sign =
            "09628650676000c8d18bf43db68e7f66dfaed230d87e6391c29eb594b7b9cc3c8d370dbd29ce62bbcf3506adb57f041d8646ae4f70a26ea5179418e738fd4372e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
    byte[] signatureBytes = Numeric.hexStringToByteArray("0x" + sign);

    ASN1Integer d_r =
            new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 0, 32)));
    ASN1Integer d_s =
            new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 32, 64)));
    ASN1EncodableVector v2 = new ASN1EncodableVector();
    v2.add(d_r);
    v2.add(d_s);
    DERSequence der = new DERSequence(v2);
    boolean b =
            SM2Algorithm.verify(
                    sourceData,
                    der.getEncoded(),
                    publicKey.substring(0, 64),
                    publicKey.substring(64, 128));
    assertTrue("Test sm2 verify", b);
}
 
Example #7
Source File: PublicKeyTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void checkPubCorrect() throws IOException {
    String defaultUserPrivateKeyAfterAes = "SzK9KCjpyVCW0T9K9r/MSlmcpkeckYKVn/D1X7fzzp18MM7yHhUHQugTxKXVJJY5XWOb4zZ79IXMBu77zmXsr0mCRnATZTUqFfWLX6tUBIw=";
    String defaultPub = "0xc5d877bff9923af55f248fb48b8907dc7d00cac3ba19b4259aebefe325510af7bd0a75e9a8e8234aa7aa58bc70510ee4bef02201a86006196da4e771c47b71b4";
    String defaultAddress = "0xf1585b8d0e08a0a00fff662e24d67ba95a438256";

    String defaultUserPrivateKey = aesUtils.aesDecrypt(defaultUserPrivateKeyAfterAes);
    System.out.println("decrypt aes");
    System.out.println(defaultUserPrivateKey);
    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 #8
Source File: SignDataTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * key pair from sign differs from local credential
 * front or sign change @param encryptType: 1 and 0 to switch from guomi and standard
 */
@Test
public void testKeyFromSign() {
    KeyStoreInfo keyStoreInfo = getKeyStoreInfoFromSign();
    Assert.assertNotNull(keyStoreInfo);
    System.out.println("keyStoreInfo: ");
    System.out.println(keyStoreInfo.getAddress());
    System.out.println(keyStoreInfo.getPublicKey());
    System.out.println(keyStoreInfo.getPrivateKey());
    // local guomi
    Credentials credentials = GenCredential.create(keyStoreInfo.getPrivateKey());
    String pub = Numeric.toHexStringWithPrefix(credentials.getEcKeyPair().getPublicKey());
    String addr = credentials.getAddress();
    System.out.println("local transfer: ");
    System.out.println(pub);
    System.out.println(addr);
    Assert.assertTrue(keyStoreInfo.getPublicKey().equals(pub));
    Assert.assertTrue(keyStoreInfo.getAddress().equals(addr));
}
 
Example #9
Source File: Transaction.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public Transaction(
        String from,
        BigInteger nonce,
        BigInteger gasPrice,
        BigInteger gasLimit,
        String to,
        BigInteger value,
        String data) {
    this.from = from;
    this.to = to;
    this.gas = gasLimit;
    this.gasPrice = gasPrice;
    this.value = value;

    if (data != null) {
        if (this.to != null && !this.to.equals("")) {
            this.data = Numeric.prependHexPrefix(data);
        } else {
            this.data = data;
        }
    }

    this.nonce = nonce;
}
 
Example #10
Source File: Contract.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Check that the contract deployed at the address associated with this smart contract wrapper
 * is in fact the contract you believe it is.
 *
 * <p>This method uses the <a href=
 * "https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode">eth_getCode</a> method to get
 * the contract byte code and validates it against the byte code stored in this smart contract
 * wrapper.
 *
 * @return true if the contract is valid
 * @throws IOException if unable to connect to web3j node
 */
public boolean isValid() throws IOException {
    if (contractBinary.equals(BIN_NOT_PROVIDED)) {
        throw new UnsupportedOperationException(
                "Contract binary not present in contract wrapper, "
                        + "please generate your wrapper using -abiFile=<file>");
    }

    if (contractAddress.equals("")) {
        throw new UnsupportedOperationException(
                "Contract binary not present, you will need to regenerate your smart "
                        + "contract wrapper with web3j v2.2.0+");
    }

    Code gcode = web3j.getCode(contractAddress, DefaultBlockParameterName.LATEST).send();
    if (gcode.hasError()) {
        return false;
    }

    String code = Numeric.cleanHexPrefix(gcode.getCode());
    // There may be multiple contracts in the Solidity bytecode, hence we only
    // check for a match with a subset
    return !code.isEmpty() && contractBinary.contains(code);
}
 
Example #11
Source File: Keys.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Checksum address encoding as per <a
 * href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md">EIP-55</a>.
 *
 * @param address a valid hex encoded address
 * @return hex encoded checksum address
 */
public static String toChecksumAddress(String address) {
    String lowercaseAddress = Numeric.cleanHexPrefix(address).toLowerCase();
    String addressHash = Numeric.cleanHexPrefix(Hash.sha3String(lowercaseAddress));

    StringBuilder result = new StringBuilder(lowercaseAddress.length() + 2);

    result.append("0x");

    for (int i = 0; i < lowercaseAddress.length(); i++) {
        if (Integer.parseInt(String.valueOf(addressHash.charAt(i)), 16) >= 8) {
            result.append(String.valueOf(lowercaseAddress.charAt(i)).toUpperCase());
        } else {
            result.append(lowercaseAddress.charAt(i));
        }
    }

    return result.toString();
}
 
Example #12
Source File: MerkleProofUtility.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Verify transaction merkle proof
 *
 * @param transactionHash
 * @param index
 * @param transactionRoot
 * @param txProof
 * @return
 */
public static boolean verifyTransaction(
        String transactionHash,
        BigInteger index,
        String transactionRoot,
        List<MerkleProofUnit> txProof) {
    String input =
            Numeric.toHexString(RlpEncoder.encode(RlpString.create(index)))
                    + transactionHash.substring(2);
    String proof = Merkle.calculateMerkleRoot(txProof, input);

    logger.debug(
            " transaction hash: {}, transaction index: {}, txProof: {}, transactionRoot: {}, proof: {}",
            transactionHash,
            index,
            txProof,
            transactionRoot,
            proof);

    return proof.equals(transactionRoot);
}
 
Example #13
Source File: KeyStoreService.java    From WeBASE-Transaction with Apache License 2.0 6 votes vote down vote up
/**
 * get KeyStoreInfo.
 * 
 * @return
 */
public KeyStoreInfo getKey() throws BaseException {
    try {
        ECKeyPair keyPair = Keys.createEcKeyPair();
        String publicKey = Numeric.toHexStringWithPrefixZeroPadded(keyPair.getPublicKey(),
                PUBLIC_KEY_LENGTH_IN_HEX);
        String privateKey = Numeric.toHexStringNoPrefix(keyPair.getPrivateKey());
        String address = "0x" + Keys.getAddress(publicKey);

        KeyStoreInfo keyStoreInfo = new KeyStoreInfo();
        keyStoreInfo.setPublicKey(publicKey);
        keyStoreInfo.setPrivateKey(privateKey);
        keyStoreInfo.setAddress(address);

        return keyStoreInfo;
    } catch (Exception e) {
        log.error("createEcKeyPair fail.");
        throw new BaseException(ConstantCode.SYSTEM_ERROR);
    }
}
 
Example #14
Source File: MerkleProofUtility.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Verify transaction merkle proof
 *
 * @param transactionRoot
 * @param transAndProof
 * @return
 */
public static boolean verifyTransaction(
        String transactionRoot, TransactionWithProof.TransAndProof transAndProof) {
    // transaction index
    Transaction transaction = transAndProof.getTransaction();
    BigInteger index = transaction.getTransactionIndex();
    String input =
            Numeric.toHexString(RlpEncoder.encode(RlpString.create(index)))
                    + transaction.getHash().substring(2);
    String proof = Merkle.calculateMerkleRoot(transAndProof.getTxProof(), input);

    logger.debug(
            " transaction hash: {}, transaction index: {}, root: {}, proof: {}",
            transaction.getHash(),
            transaction.getTransactionIndex(),
            transactionRoot,
            proof);

    return proof.equals(transactionRoot);
}
 
Example #15
Source File: RawTransactionManager.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public SendTransaction signAndSend(
        RawTransaction rawTransaction, TransactionSucCallback callback) throws IOException {

    byte[] signedMessage;

    if (chainId > ChainId.NONE) {
        signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials);
    } else {
        signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    }

    String hexValue = Numeric.toHexString(signedMessage);
    Request<?, SendTransaction> request = web3j.sendRawTransaction(hexValue);
    request.setNeedTransCallback(true);
    request.setTransactionSucCallback(callback);
    request.sendOnly();

    return null;
}
 
Example #16
Source File: TransactionDecoderTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecoding() throws Exception {
    BigInteger gasPrice = BigInteger.ONE;
    BigInteger gasLimit = BigInteger.TEN;
    String to = "0x0add5355";
    BigInteger value = BigInteger.valueOf(Long.MAX_VALUE);
    BigInteger randomid = new BigInteger("500");
    BigInteger blockLimit = new BigInteger("501");
    RawTransaction rawTransaction =
            RawTransaction.createContractTransaction(
                    randomid, gasPrice, gasLimit, blockLimit, value, "0x0000000000");
    byte[] encodedMessage = TransactionEncoder.encode(rawTransaction);
    String hexMessage = Numeric.toHexString(encodedMessage);

    RawTransaction result = TransactionDecoder.decode(hexMessage);
    assertNotNull(result);
    assertEquals(blockLimit, result.getBlockLimit());
    assertEquals(gasPrice, result.getGasPrice());
    assertEquals(gasLimit, result.getGasLimit());
    assertEquals("0x", result.getTo());
    assertEquals(value, result.getValue());
    assertEquals("0000000000", result.getData());
}
 
Example #17
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 #18
Source File: TypeDecoder.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
static DynamicBytes decodeDynamicBytes(String input, int offset) {
    int encodedLength = decodeUintAsInt(input, offset);
    int hexStringEncodedLength = encodedLength << 1;

    int valueOffset = offset + MAX_BYTE_LENGTH_FOR_HEX_STRING;

    String data = input.substring(valueOffset, valueOffset + hexStringEncodedLength);
    byte[] bytes = Numeric.hexStringToByteArray(data);

    return new DynamicBytes(bytes);
}
 
Example #19
Source File: TransactionDecoderTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodingSigned() throws Exception {
    BigInteger gasPrice = BigInteger.ONE;
    BigInteger gasLimit = BigInteger.TEN;
    String to = "0x0add5355";
    BigInteger value = BigInteger.valueOf(Long.MAX_VALUE);
    BigInteger randomid = new BigInteger("500");
    BigInteger blockLimit = new BigInteger("501");
    RawTransaction rawTransaction =
            RawTransaction.createEtherTransaction(
                    randomid, gasPrice, gasLimit, blockLimit, to, value);
    byte[] signedMessage =
            TransactionEncoder.signMessage(rawTransaction, SampleKeys.CREDENTIALS);
    String hexMessage = Numeric.toHexString(signedMessage);

    RawTransaction result = TransactionDecoder.decode(hexMessage);
    assertNotNull(result);
    assertEquals(randomid, result.getRandomid());
    assertEquals(gasPrice, result.getGasPrice());
    assertEquals(gasLimit, result.getGasLimit());
    assertEquals(to, result.getTo());
    assertEquals(value, result.getValue());
    assertEquals("", result.getData());
    assertTrue(result instanceof SignedRawTransaction);
    SignedRawTransaction signedResult = (SignedRawTransaction) result;
    assertNotNull(signedResult.getSignatureData());
    Sign.SignatureData signatureData = signedResult.getSignatureData();
    byte[] encodedTransaction = TransactionEncoder.encode(rawTransaction);
    BigInteger key = Sign.signedMessageToKey(encodedTransaction, signatureData);
    assertEquals(key, SampleKeys.PUBLIC_KEY);
    assertEquals(SampleKeys.ADDRESS, signedResult.getFrom());
    signedResult.verify(SampleKeys.ADDRESS);
    assertNull(signedResult.getChainId());
}
 
Example #20
Source File: SM2Sign.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * The new sm2 signature algorithm with better performance
 *
 * @param message
 * @param ecKeyPair
 * @return
 */
public static Sign.SignatureData sign2(byte[] message, ECKeyPair ecKeyPair) {

    SM2Signer sm2Signer = new SM2Signer();

    ECPrivateKeyParameters eCPrivateKeyParameters =
            new ECPrivateKeyParameters(ecKeyPair.getPrivateKey(), eCDomainParameters);

    sm2Signer.initWithCache(
            true,
            new ParametersWithID(new ParametersWithRandom(eCPrivateKeyParameters), identValue));

    org.bouncycastle.crypto.digests.SM3Digest sm3Digest =
            new org.bouncycastle.crypto.digests.SM3Digest();

    byte[] md = new byte[sm3Digest.getDigestSize()];
    sm3Digest.update(message, 0, message.length);
    sm3Digest.doFinal(md, 0);

    sm2Signer.update(md, 0, md.length);

    byte[] r = null;
    byte[] s = null;
    byte[] pub = null;

    try {
        BigInteger[] bigIntegers = sm2Signer.generateSignature2();

        pub = Numeric.toBytesPadded(ecKeyPair.getPublicKey(), 64);
        r = SM2Algorithm.getEncoded(bigIntegers[0]);
        s = SM2Algorithm.getEncoded(bigIntegers[1]);
    } catch (CryptoException e) {
        throw new RuntimeException(e);
    }

    return new Sign.SignatureData((byte) 0, r, s, pub);
}
 
Example #21
Source File: TransactionReceipt.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
public boolean isStatusOK() {
    if (null == status) {
        return true;
    }

    try {
        BigInteger statusQuantity = Numeric.decodeQuantity(status);
        return BigInteger.ZERO.equals(statusQuantity);
    } catch (Exception e) {
        return false;
    }
}
 
Example #22
Source File: Tools.java    From evidenceSample with Apache License 2.0 5 votes vote down vote up
static public  String  signatureDataToString(Sign.SignatureData signatureData)
{
    byte[] byte_3 = new byte[1+signatureData.getR().length+signatureData.getS().length];
    byte_3[0] = signatureData.getV();
    System.arraycopy(signatureData.getR(), 0, byte_3, 1, signatureData.getR().length);
    System.arraycopy(signatureData.getS(), 0, byte_3, signatureData.getR().length+1, signatureData.getS().length);
    return  Numeric.toHexString(byte_3,0,byte_3.length,false);
}
 
Example #23
Source File: Log.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private BigInteger convert(String value) {
    if (value != null) {
        return Numeric.decodeQuantity(value);
    } else {
        return null;
    }
}
 
Example #24
Source File: KeysTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAddressSmallPublicKey() {
    byte[] address =
            Keys.getAddress(
                    Numeric.toBytesPadded(BigInteger.valueOf(0x1234), Keys.PUBLIC_KEY_SIZE));
    String expected = Numeric.toHexStringNoPrefix(address);

    assertThat(Keys.getAddress("0x1234"), equalTo(expected));
}
 
Example #25
Source File: Tools.java    From evidenceSample with Apache License 2.0 5 votes vote down vote up
static public Sign.SignatureData stringToSignatureData(String signatureData)
{
    byte[] byte_3 = Numeric.hexStringToByteArray(signatureData);
    byte[] signR = new byte[32];
    System.arraycopy(byte_3, 1, signR, 0, signR.length);
    byte[] signS = new byte[32];
    System.arraycopy(byte_3, 1+signR.length, signS, 0, signS.length);
    return  new Sign.SignatureData(byte_3[0],signR,signS);
}
 
Example #26
Source File: TopicTools.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static String byteNToTopic(byte[] b) {
    // byte[] can't be more than 32 byte
    if (b.length > 32) {
        throw new IllegalArgumentException("byteN can't be more than 32 byte");
    }

    Bytes bs = new Bytes(b.length, b);
    return Numeric.prependHexPrefix(TypeEncoder.encode(bs));
}
 
Example #27
Source File: TopicTools.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static String addressToTopic(String s) {

        if (!WalletUtils.isValidAddress(s)) {
            throw new IllegalArgumentException("invalid address");
        }

        return "0x000000000000000000000000" + Numeric.cleanHexPrefix(s);
    }
 
Example #28
Source File: TopicTools.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static String boolToTopic(boolean b) {
    if (b) {
        return Numeric.toHexStringWithPrefixZeroPadded(BigInteger.ONE, 64);
    } else {
        return Numeric.toHexStringWithPrefixZeroPadded(BigInteger.ZERO, 64);
    }
}
 
Example #29
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Request<?, BcosTransaction> getTransactionByBlockNumberAndIndex(
        DefaultBlockParameter defaultBlockParameter, BigInteger transactionIndex) {
    return new Request<>(
            "getTransactionByBlockNumberAndIndex",
            Arrays.asList(
                    groupId,
                    defaultBlockParameter.getValue(),
                    Numeric.encodeQuantity(transactionIndex)),
            web3jService,
            BcosTransaction.class);
}
 
Example #30
Source File: MerkleProofUtility.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Verify transaction receipt merkle proof
 *
 * @param receiptRoot
 * @param transactionReceipt
 * @param receiptProof
 * @return
 */
public static boolean verifyTransactionReceipt(
        String receiptRoot,
        TransactionReceipt transactionReceipt,
        List<MerkleProofUnit> receiptProof) {

    if (!transactionReceipt.getGasUsedRaw().startsWith("0x")) {
        transactionReceipt.setGasUsed("0x" + transactionReceipt.getGasUsed().toString(16));
    }

    // transaction index
    byte[] byteIndex =
            RlpEncoder.encode(RlpString.create(transactionReceipt.getTransactionIndex()));

    String receiptRlp = ReceiptEncoder.encode(transactionReceipt);
    String rlpHash = Hash.sha3(receiptRlp);
    String input = Numeric.toHexString(byteIndex) + rlpHash.substring(2);

    String proof = Merkle.calculateMerkleRoot(receiptProof, input);

    logger.debug(
            " transaction hash: {}, transactionReceipt: {}, receiptProof: {}, receiptRoot: {}, proof: {}",
            transactionReceipt.getTransactionHash(),
            transactionReceipt,
            receiptProof,
            receiptRoot,
            proof);

    return proof.equals(receiptRoot);
}