PacktPublishing / Blockchain-By-Example

Blockchain By Example published by Packt
MIT License
76 stars 57 forks source link

Chapter One Question #2

Closed joshineveryday closed 4 years ago

joshineveryday commented 4 years ago

Hi @bellaj I started your book and am having issues getting the first programming example to work. ChainSo calls are failing on me. I made an issue asking about this on the bitcoinjs-lib repo, thinking maybe you may be able to lend a hand here: https://github.com/bitcoinjs/bitcoinjs-lib/issues/1453

Would be a much appreciated! :)

junderw commented 4 years ago
> 0.04109432 * 100000000
4109431.9999999995
> parseInt(0.04109432 * 100000000)
4109431

The answer was that JavaScript sometimes randomly decides to do stuff like above, and it depends on the value.

ie. these are fine

> 0.04109431 * 100000000
4109431
> 0.04109433 * 100000000
4109433
> 0.04109437 * 100000000
4109437

@bellaj you should try and avoid dealing with BTC values in examples and only use integer satoshi values.

bellaj commented 4 years ago

in the original script it's var amount=Number.parseInt(response.data.txs[index].value*100000000); not 0.04109431 * 100000000

junderw commented 4 years ago

my point is that your example uses an api that returns BTC value.

Some BTC values when multiplied by 100000000 and run through parseInt will be off by 1 satoshi.

If your api response.data.txs[index].value was 0.04109432

multiplying should give you 4109432

but instead JavaScript turns it into 4109431

In segwit, you must sign the value exactly, so if you plan to use BTC amounts from the API you must use a big-number library to guarantee accuracy.

Or just use satoshi values, and this problem goes away.