Bit-Wasp/bitcoin-lib-php — pull request #28 by rubensayshi (2014-11-06 16:38:29+00:00)
Title: sign p2sh invalid signature (random K) 

this PR isn't a proper fix, but I figured it was the easiest way to share some code to show the problem.
*disclaimer;* I'm not a crypto-god, so I can't explain why it doesn't work and neither why I can fix it, I'm hoping one of you guys can :D

I was testing signing a p2sh in 2 steps, first signing once with the 1st PK and then signing again with the 2nd PK and I ran into an inconsistency.
When signing with the 2nd PK it randomly fails to detect the previous signature, as in the `sign_count` would be 0.

When digging in deeper I figured it was because of the random bytes used as the `random_k` for `PrivateKey::sign`, digging a little deeper I figured out that the signature produced wasn't valid all the time if I would run it through `is_canonical_signature`.
My current 'fix' is wrapping it in a `do {} while();` until it produces a valid signature, where 10 tries weren't enough so I changed the max tries to 100 ... but it's random so 100 isn't very safe either!

I hope you guys understand this problem better than I do, all that I can figure out is that bitcore explicitly doesn't support the 'determenistic K' when signing (https://github.com/bitpay/bitcore/blob/master/lib/Key.js#L14)...

I doubt looping until it validates is the best aproach, but I see the same in bitcore being done -.-'
It's also not the fastest process to loop ...

The `php examples/sign_p2sh_stepbystep.php` script demostrates/tests the case, if you change the `$tries_left` in `RawTransaction` to 1 or anything below 10 you'll regularly see the test case failing.