Comments (15)
lets consider i have function whose input parameter is
-
bytes32
-
bytes32[ ] // array of type bytes 32
-
uint8
which looks like:
function abc(bytes32 id, bytes32[ ] name,uint8 version) returns(bool)
{
//
}
so now to provoke the function (using remix) you have to pass parameters which looks like:
"0x12",["0x1262","0x12","0x12"],8
from web3j.
After struggling with this for a while I decided to just pass my value as a string and convert it to a bytes32 once it enters the contract...
This works just fine.
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
from web3j.
@conor10 @thedoctor Can you please answer this?
from web3j.
@qnimate hash.getBytes()
is going to give you a java byte[]
– you can convert that to a Bytes32
if and only if it has a length == 32. Check the length of hash.getBytes()
. Depending on what kind of object hash
is, getBytes()
might not be what you want to call.
from web3j.
@thedoctor hash
is a Java string. My hash
length is 64 because it's in hexadecimal format. bytes32 is supposed to be 32 length. How do I convert hash to 32 byte length? It's a sha256 hash.
from web3j.
Okay, yeah that's not what you want. If hash
is a string, then getBytes
will give you the byte encoding of the string in whatever your default charset is (probably utf8).
I'm guessing your hash is hex encoded? If so, you want to decode the hex to a byte array –– lots of ways to do that, here's one from ethereumJ that handles the 0x
prefix:
new Bytes32(org.ethereum.jsonrpc.TypeConverter.StringHexToByteArray(hash))
from web3j.
@thedoctor anyway to do it without using ethereumJ?
from web3j.
Yes, many:
https://stackoverflow.com/questions/8890174/in-java-how-do-i-convert-a-hex-string-to-a-byte
https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
https://commons.apache.org/proper/commons-codec/
https://google.github.io/guava/releases/16.0/api/docs/com/google/common/io/BaseEncoding.html
Note: if your hash has a 0x
prefix, you'll have to strip it first if you use any of those methods.
from web3j.
@thedoctor I am using this to convert byte[] b = new BigInteger(s,16).toByteArray();
If the string length is 64 then the byte[] length shows as 33 but when the string length is 63 then the byte[] length shows as 32. Not sure what's wrong. Any idea?
The sha256 hash in should be a 64 length string right?
from web3j.
@thedoctor seems like this is the issue http://stackoverflow.com/questions/33536253/java-the-length-of-the-byte-array-seems-to-be-wrong-from-converting-a-string-of
from web3j.
Found solution
Arrays.copyOfRange(new BigInteger(hash, 16).toByteArray(), 1, 33)
@thedoctor Thanks a lot for the help.
from web3j.
Ahhhh, actually @qnimate that will eventually give you problems. You shouldn't use the BigInteger conversion method (as it says in the most-upvoted answer to the question you got that from) because it doesn't work with leading zeros.
If you want a quick one-liner with no dependencies, do this:
javax.xml.bind.DatatypeConverter.parseHexBinary(hash);
General advice: When you're handling cryptographic primitives, even if they're not sensitive, it's worth your time to investigate thoroughly the proper way to handle them. Copying from SO without understanding what's happening is not advised.
from web3j.
@qnimate - web3j already has a number of helper functions for conversions betwen hex strings, BigIntegers and byte arrays. See https://github.com/web3j/web3j/blob/master/src/main/java/org/web3j/utils/Numeric.java#L157 for converting a hex string to a byte array.
@thedoctor - thanks for chipping in here.
from web3j.
Huh, look at that. I actually looked in that package for something that would avoid external dependencies last night – but I only checked Bytes
Convert
and Strings
from web3j.
This worked for me, only tested for ASCII, may/may not work for UTF... Is there any better method?
ASCII String to Bytes32:
public static Bytes32 stringToBytes32(String string) {
byte[] byteValue = string.getBytes();
byte[] byteValueLen32 = new byte[32];
System.arraycopy(byteValue, 0, byteValueLen32, 0, byteValue.length);
return new Bytes32(byteValueLen32);
}
Bytes32 to ASCII String:
StringUtils.newStringUsAscii(varTypeBytes32.getValue())
from web3j.
Related Issues (20)
- log filter not work, case: on reinstallFilter() called, if getInitialFilterLogs() throw Exception, schedule is Cancelled on reinstallFilter.
- Generated Contract Error: Cannot cast from List to byte[]
- Wrapper Generation with Array of Structs Parameter still an issue in 4.10.3
- Could you please help release the package? This bug has affected normal use: https://github.com/web3j/web3j/pull/1962 HOT 1
- Filter Exception, Invalid request: filter not found
- Generated wrapper around struct containing a `address[]` member can't be instantiated
- FastRawTransactionManager's resetNonce() will bring its nonce field out of sync
- Allow the use of a struct without having a corresponding Java class
- Update BouncyCastle in org.web3j:core:4.8.7-android HOT 3
- Build fails due to dependency jc-kzg-4844 since version 4.11.0 HOT 7
- Create / demonstrate in tests method for recovering address from signTypedData
- CVE-2023-33201 transitive vulnerable dependency
- Solidity multidimensional array as return
- Quick Start command not working HOT 1
- Error: Stack too deep. HOT 2
- Could not set unknown property 'outputDir' for Main Solidity Sources of type org.gradle.api.internal.file.DefaultSourceDirectorySet. HOT 4
- Fail to install web3j cli on Linux HOT 1
- what is the output parameter (Type referrence) for method returning empty list e.g "outputs": [] HOT 1
- Generated Java code does not compile (symbol LinkReference does not exist) HOT 1
- DefaultFunctionEncoder calculates offset incorrectly for nested structs HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from web3j.