Web3j
無法使用 web3j 從交易中解碼輸入數據
我正在使用 web3j 創建事務並在該事務中傳遞一些私有數據。該交易也正在被探勘。我已經訂閱了已開采的區塊,我正在獲取已添加到已開採區塊中的交易。我想檢索之前傳遞的輸入數據,但無法獲取。請在這裡幫助我。
使用 web3j 進行交易的程式碼:
RawTransactionManager rawTransactionManager = new RawTransactionManager(web3j ,credentials,100,1000 * 15); EthSendTransaction send = rawTransactionManager.sendTransaction(gasPrice, Transfer.GAS_LIMIT, toAddress, "<some private data>", BigInteger.valueOf(1)); String hash = send.getTransactionHash();
我也正確地得到了雜湊。然後,我訂閱了這些塊,如下所示:
Subscription subscriptionToBlocks = web3j.blockObservable(true).subscribe(block -> { List<TransactionResult> transactions = block.getBlock().getTransactions(); if(transactions.size > 0){ transactions.forEach(tx -> { EthBlock.TransactionObject transaction = (EthBlock.TransactionObject) tx.get(); System.out.println("transaction data:"+transaction.getInput()); }
但這會導致十六進製字元串,但是,我希望它再次解密以進一步處理它。讓我知道如何獲取發送的原始數據
大概您
<some private data>
是 ASCII 編碼的,而乙太坊將所有內容轉換為字節碼(機器可讀)並以十六進制(base16)返回所有內容,這會弄亂編碼。因此,解決方案包括在發送交易之前將您的消息編碼為 ASCII 十六進制。
public static String ASCIItoHEX(String ascii) { // Initialize final String String hex = ""; // Make a loop to iterate through // every character of ascii string for (int i = 0; i < ascii.length(); i++) { // take a char from // position i of string char ch = ascii.charAt(i); // cast char to integer and // find its ascii value int in = (int)ch; // change this ascii value // integer to hexadecimal value String part = Integer.toHexString(in); // add this hexadecimal value // to final string. hex += part; } // return the final string hex return hex; }
因此,當您向您發送交易時,您只需將您的消息轉換為十六進制:
RawTransactionManager rawTransactionManager = new RawTransactionManager(web3j, credentials, 4, 1000 * 15); EthSendTransaction send = rawTransactionManager.sendTransaction(BigInteger.valueOf(1000000000000L), BigInteger.valueOf(100000L), "0xDD6325C45aE6fAbD028D19fa1539663Df14813a8", ASCIItoHEX("hello"), BigInteger.valueOf(1)); String hash = send.getTransactionHash();
您現在可以看到輸入數據是正確的:https ://rinkeby.etherscan.io/tx/0xd3b67f1e67c4607cb0d6a2f02066d1d382843da0619d9f02bb8da5f1fc0bb66a
當您在交易被探勘後獲得交易時,您只需要做相反的事情:
String hexString = transaction.getInput(); // Remove the prefix 0x if(hexString.startsWith("0x")) { hexString = hexString.substring(2); } // Convert Base16 into a byte array byte[] byteArray = new BigInteger(hexString, 16).toByteArray(); // Pass the byte array to a String will re-encode it in ASCII. String asciiString = new String(byteArray); System.out.println(hexString+"="+asciiString);
68656c6c6f=你好
有用的連結