I Call SmartContract Token ERC20, Why Show Hashing Output? - javascript

I do not know why with this, even though in the previous version (web3 + Metamask) can issue real data. But now used as hashing (output). I took the example in the code and output below (to get the TotalSupply on the ERC20 Token):
Output : 0x18160ddd
const contractInstance = web3.eth.contract(contractAbi).at(contractAddress);
const total_supply = contractInstance.totalSupply.getData();
console.log(total_supply);
How to showing real data? In a sense it doesn't come out hashing. Thanks

.getData() returns the ABI-encoded input you would have to send to the smart contract to invoke that method.
If you want to actually call the smart contract, use .call() instead.

Related

Xero webhooks with Node Red; OK, than not ok

I have been dealing with cryptography craziness since yesterday, I 've literally lost my sleep over this.
I am implementing a node red solution to get webhooks from Xero to be written in a custom app. I have experienced a lot of issues with the payload and how it needs to be stringified and how needs to be hashed, but eventually figured it out thanks to a Github fellow that posted this code to get the body to its 'raw' state
let msgPayloadRaw = JSON.stringify(msg.payload).split(':').join(': ').split(': [').join(':[').split(',"entropy"').join(', "entropy"');
I then create a sha256 base64 hash to check against the header value using the following js code
var cryptojs = context.global.cryptojs;
const webhookKey = 'MyWebhookKeyHere';
let msgPayloadRaw = JSON.stringify(msg.payload).split(':').join(': ').split(': [').join(':[').split(',"entropy"').join(', "entropy"');
let bdata = new Buffer(msgPayloadRaw).toString();
let ciphertext = cryptojs.HmacSHA256(bdata, webhookKey );
let base64encoded = cryptojs.enc.Base64.stringify(ciphertext);
msg.payload = base64encoded;
return msg;
Now everything should work great, but I get a crazy result showcased in this recording, where the web hooks intent status turns to 'OK', and some seconds later returns to this error:
Retry
We haven’t received a successful response on the most recent delivery attempt and will retry sending with decreasing frequency for an overall period of 24 hours.
Response not 200. Learn more
Last sent at 2022-06-22 11:48:28 UTC
What's the problem ?
The problem relies in the http input, where node red parsed the body.
Body needs to be hashed. The body in the http request is like that
{"events":[],"firstEventSequence": 0,"lastEventSequence": 0, "entropy": "IVMMHNWPBAZYRZJRCUAQ"}
Notice the spaces after each :
Node Red converts that body to JSON object. When I do JSON.stringify(msg.payload); I will get the following
{"events":[],"firstEventSequence":0,"lastEventSequence":0, "entropy":"IVMMHNWPBAZYRZJRCUAQ"}
which is obviously the same, but technically it is not (due to spaces) and when hashed it generates a different hash value.
The GitHub fellow did that that walkround
JSON.stringify(msg.payload).split(':').join(': ').split(': [').join(':[').split(',"entropy"').join(', "entropy"');
So in order to solve this, I need to find a way to get the raw http input, instead of the parsed one that node red is providing.
Any ideas how to get the raw input ?
Sort answer: you don't.
The raw body is not available if the Content-Type header is set to application/json the bodyParser will kick in and generate the matching JSON object that is passed as the msg.payload.
the httpNodeMiddleware is attached after the bodyParser so the body has already been changed.

Verify Stripe web-hook manually

I am trying to manually verify web-hook:
const stripeSecret = createHmac('sha256', STRIPE_SIGNING_SECRET)
.update(event.body)
.digest('hex');
if(stripeSecret !== keyFromHeader) {
throw err();
}
But it is not matched with Stripe secret key which is received in header.
Here is event data which I am also trying to use in Stripe API (it also fails):
it's not event.body you should hash According to the documentation (https://stripe.com/docs/webhooks/signatures#verify-manually
) its a concatenation of :
The timestamp (as a string)
The character .
The actual JSON payload (i.e., the request body) => JSON.stringify(req.body)
you will need to parse this to get the timestamp (the xxxxx in the "t=xxxxx" part)
const sig = request.headers['stripe-signature'];
if you give me a sample stripe signature header i can try a code sample.
event.body might not be enough — it's very common in Node server environments for that to be a "parsed" version of the incoming request body, and instead you need to make sure to access the actual raw JSON string in the body — that's what Stripe's signature is computed against. It can be a little tricky!
https://github.com/stripe/stripe-node/tree/master/examples/webhook-signing
(and many examples contributed for various frameworks at https://github.com/stripe/stripe-node/issues/341 )
Also, is there a specific reason to do this manually and not just use Stripe's Node library? :)

Generate card_error in stripe.js while testing

I dont know this can be done or not, but i was wondering is there any way to generate card_error on stripe for testing?
To clarify my question here's what I want to do:
Stripe provides varieties of card numbers for testing purposes
(here). Along with this it also provides methods for form
validation(eg. I enter 34/2013 as expiry date and i'll get invalid
date error by validation then and there).
But i want to create a situation where a
user enters an expiry date which is a valid date (say 12/2015) but
its not the real expiry date of the card, so that on sending this
information to stripe, i recieve an error in json form named
card_error. (here)
How can this be done?
There are two approaches you could take to this.
You pass the stripe API call a callback function. This callback is the unit of code that you want to test with the card_error type of response
'test card_error is handled correctly': function() {
var response = {
type: 'card_error',
message: 'The human readable message',
code: 'invalid_cvc'
myStripeCallback(response)
// Make assertions down here about what happened when
// you called the function with the error message
// Maybe it emailed you, maybe it displayed a message
// to the user. I would then probably make another test
// for each `code` that I cared about.
}
The second approach would be to mock out the stripe api call entirely. Check that it was called with the right arguments and then call the provided callback with the error response that you wanted to deal with in that test.
Im sorry, turned out to be stripe already has special codes for this purpose. I over looked that part of the page despite going through the page several times.. stupid me! :-/
Anyways here are the codes:
source: https://stripe.com/docs/testing

How do I access the data given in the onHttpRequest function in the Firefox Add-on SDK?

I am trying to read the response headers 'name' and 'value'. The end goal is to compare them to some pre-set name and a value to see if they match.
Here is what I have so far, it's the function that run every time I get a response header.
var observer = require("observer-service");
observer.add("http-on-examine-response", onHttpRequest);
function onHttpRequest(subject, data)
{
console.log("request subject...." + subject);
console.log("request data...." + data);
}
The output is as follows:
request subject....[xpconnect wrapped nsISupports]
request data....null
I was hoping to know how to get the rest of the data out of the response.
Any help would be great, thanks.
The subject for http-on-examime-response implements nsIHttpChannel, among some other things. You may use .QueryInterface() or instanceof (which internally kinda uses QueryInteface, so that this works as well) to get to that interface.
const {Ci} = require("chrome");
if (subject instanceof Ci.nsIHttpChannel) {
console.log("content-type", subject.getResponseHeader("content-type"));
subject.visitResponseHeaders(function(header, value) {
console.log(header, value);
});
}
There are a couple of other questions around here going into more detail on how to use these notifications... Also, mxr can help a lot checkout out what interfaces there are, how it fits together and how one could use it (in particular the existing tests are great to see some uses for all kinds of stuff).
There is also the "nsITraceableChannel, Intercept HTTP Traffic" article going into more details, e.g. on how to use nsITraceableChannel to get the payload data from such a channel.

Twitter, JavaScript & OAuth: failed to validate oauth signature and token

Im trying to implement OAuth using JavaScript, but when I make my request to http://api.twitter.com/oauth/request_token I am getting the above message in the response ("failed to validate oauth signature and token").
As far as I can tell I'm including all the correct parameters, both in the encoding of the signature base:
basestring: (consumer key removed for security)
POST&http%3A%2F%2Ftwitter.com%2Foauth%2Frequest_token%26oauth_callback
%3Doob%26oauth_consumer_key
%3D11111111111111111111112222222222222%26oauth_nonce
%3DO3cHsSXrfnzT%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp
%3D1275928008%26oauth_version%3D1.0
consumer secret: (removed for security)
11111111111111111111112222222222222&
Signature:
R3eHMuQ04F37+xPJSIsoo0aMzc8
Post Data: (consumer key removed for security)
oauth_callback=oob&oauth_consumer_key=11111111111111111111112222222222222&oauth_signature_method=HMAC-SHA1&oauth_signature=pjDh8jkp89ThBtzzB9dQmxQfcg&oauth_timestamp=1275928413&oauth_nonce=qyq3Jhn8rtTZ&oauth_version=1.0
And I've checked that the clock is correct on my device as that's the only real result I can find for this problem :( The nonce is unique and generated every time it runs...
Unfortunately I don't know where to look now. I can't spot anything obvious. I've re-written the entire request twice - once using the oauth.js library and once completely manually, but in both cases it fails with the same error!
Any suggestions?
Cheers
Perhaps the same as this question - which links to a discussin on twitter: apparently client side javascript with oob is not allowed!?!?
Your signature looks wrong, it should always end with a =. Here is an example of a valid one: "YEBbMFDYmp6DvZ3qW1aCx8q7kTc=". Your base string looks right, so I think you've made a mistake with your signature key.
In C#, here is how I built my signature key,
string signatureKey = Uri.EscapeDataString( consumer_secret ) + "&";
var hmacsha1 = new HMACSHA1( new ASCIIEncoding().GetBytes(signatureKey));
string signatureString = Convert.ToBase64String(
hmacsha1.ComputeHash(
new ASCIIEncoding().GetBytes( signatureBaseString ) ) );
string oauth_signature = signatureString;
More info on this process: https://www.dinochiesa.net/?p=17

Categories