Commit graph

51 commits

Author SHA1 Message Date
Olaoluwa Osuntokun
b686b0a8eb
Merge pull request #1429 from cfromknecht/btcec-double-is-on-curve
btcec: optimize square root using fieldVal
2019-10-09 17:54:42 -07:00
Conner Fromknecht
2340ad388c
btcec/btcec: deprecate QPlus1Div4() in favor of Q()
The previous naming suggested that the value ((P+1)/4+1)/4 was being
returned, when in fact the returned value is simply (P+1)/4. The old
method is superseded by Q().
2019-10-02 18:22:17 -07:00
Conner Fromknecht
c7d523f83c
btcec/pubkey: optimize decompressPoint using fieldVals
This commit optimizes the decompressPoint subroutine, used in extracting
compressed pubkeys and performing pubkey recovery. We do so by replacing
the use of big.Int.Exp with with square-and-multiply exponentiation of
btcec's more optimized fieldVals, reducing the overall latency and
memory requirements of decompressPoint.

Instead of operating on bits of Q = (P+1)/4, the exponentiation applies
the square-and-multiply operations on full bytes of Q.  Compared to the
original speedup. Compared the bit-wise version, the improvement is
roughly 10%.

A new pair fieldVal methods called Sqrt and SqrtVal are added, which
applies the square-and-multiply exponentiation using precomputed
byte-slice of the value Q.

Comparison against big.Int sqrt and SAM sqrt over bytes of Q:

benchmark                            old ns/op     new ns/op     delta
BenchmarkParseCompressedPubKey-8     35545         23119         -34.96%

benchmark                            old allocs     new allocs     delta
BenchmarkParseCompressedPubKey-8     35             6            -82.86%

benchmark                            old bytes     new bytes     delta
BenchmarkParseCompressedPubKey-8     2777          256           -90.78%
2019-10-02 18:21:59 -07:00
Conner Fromknecht
39500ed5ed
btcec/pubkey: remove redundant checks from compressed pubkey parsing
As of https://github.com/btcsuite/btcd/pull/1193, decompressPoint now
validates that the point is on the curve. The x and y cooordinates are
also implicitly <= P, since the modular reduction is applied to both
before the method returns. The checks are moved so that they are still
applied when parsing an uncompressed pubkey, as the checks are not
redundant in that path.
2019-10-02 15:31:23 -07:00
Conner Fromknecht
4aeb189fc4
btcec: benchmark ParsePubKey for compressed keys 2019-10-02 15:31:23 -07:00
Sad Pencil
ba530c4abb btcec: correct the comment of recoverKeyFromSignature 2019-09-25 17:28:57 -07:00
Wilmer Paulino
545bc5d474
txscript: handle variable length P2PKH signatures in ComputePkScript
Since P2PKH signatures have variable lengths, we would attempt to parse
P2PKH scripts as P2SH if they didn't fit the previous length
constraints.
2019-06-03 13:55:24 -07:00
junderw
3dcf298fed Fix one-off bug in signRFC6979 2018-11-23 13:02:23 -06:00
Julian Meyer
66d33037ec btcec/signature: updated comment to reference constant instead of value 2018-09-20 20:24:03 -07:00
Julian Meyer
8965887ca4 btcec/signature: moved minimum signature length to a constant 2018-09-20 20:19:11 -07:00
Julian Meyer
db8e412dc6 btcec/signature: fix DoS bug with signature parsing 2018-09-20 09:26:45 -07:00
Conner Fromknecht
347cd3839f
btcec/signature_test: adds small pubkey recovery tests 2018-06-12 17:31:03 -07:00
Conner Fromknecht
bd1d6c9148
btcec/pubkey: verify decompressed y-coord is sqroot 2018-05-29 17:06:32 -07:00
Olaoluwa Osuntokun
4b968f7e18 btcec: remove obsolete test 2018-05-15 20:47:29 -07:00
Olaoluwa Osuntokun
253b37c17f btcec: format btcec_test.go with gofmt -s 2018-05-15 20:47:29 -07:00
Nicola 'tekNico' Larosa
11fcd83963 btcd/multi: fix a number of typos in comments. 2018-01-25 23:23:59 -06:00
Steven Roose
fb43a179cb btcec: Add case to signature serialization test
It adds the case where the S value of the signature is bigger than the
half of the order of the curve.
2017-10-13 03:37:29 -05:00
Steven Roose
79445fbd97 btcec: Prevent static initialization of S256
This is achieved by introducing a new variable `halfOrder` on the
KoblitzCurve struct that is half the order.
2017-10-13 03:37:29 -05:00
Dave Collins
2a753ae9c7
btcec: Regenerate and update precomputed data.
This regenerates the precomputed secp256k1 byte points used to optimize
scalar multiplication.  This should have been done as part of the
normalization correction.
2017-08-18 12:53:28 -05:00
Olaoluwa Osuntokun
65feec33e0 btcec: add new IsCompressedPubKey function
This commit adds a new function to btcec: IsCompressedPubKey. This
function returns true iff the passed serialized public key is encoded
in compressed format.
2017-08-13 23:17:40 -05:00
Jimmy Song
1bdb713285 btcec: Slightly optimize NAF and add several tests.
This slightly optimizes the NAF function by avoiding returning the
unused bit when there is not a carry.

It also adds a bunch of additional unit tests which I made while
debugging.
2017-06-07 20:43:48 -05:00
Dave Collins
1238b7e55a
btcec: Optimize and correct normalize.
This modifies the normalize function of the internal field value to
both optimize it and address an issue where the reduction could
lead to an incorrect result with a small range of values.  It also adds
tests to ensure the behavior is correct.

The following benchmark shows the relative speedups as a result of the
optimization on my system.  In particular, the changes result in
approximately a 14% speedup in Normalize, which ultimately translates to
a 2% speedup in signature verifies.

benchmark                        old ns/op     new ns/op     delta
--------------------------------------------------------------------
BenchmarkAddJacobian             1364          1289          -5.50%
BenchmarkAddJacobianNotZOne      3150          3091          -1.87%
BenchmarkScalarBaseMult          134117        132816        -0.97%
BenchmarkScalarBaseMultLarge     135067        132966        -1.56%
BenchmarkScalarMult              411218        402217        -2.19%
BenchmarkSigVerify               671585        657833        -2.05%
BenchmarkFieldNormalize          36.0          31.0          -13.89%
2017-06-07 20:43:36 -05:00
Dave Collins
711e7dbb2e
btcec: Add benchmark for field normalization. 2017-06-07 20:43:27 -05:00
Dave Collins
9918e2a561
multi: Update markdown files for GFM changes.
The github markdown interpreter has been changed such that it no longer
allows spaces in between the brackets and parenthesis of links and now
requires a newline in between anchors and other formatting.  This
updates all of the markdown files accordingly.

While here, it also corrects a couple of inconsistencies in some of the
README.md files.
2017-05-25 12:06:16 -05:00
Dave Collins
efa50e6abc
multi: Simplify code per gosimple linter.
This simplifies the code based on the recommendations of the gosimple
lint tool.

Also, it increases the deadline for the linters to run to 10 minutes and
reduces the number of threads that is uses. This is being done because
the Travis environment has become increasingly slower and it also seems
to be hampered by too many threads running concurrently.
2017-03-22 15:34:13 -05:00
David Hill
ab0f30c00d mining: drop getwork support.
Since the Midstate is no longer needed, switch to using
crypto/sha256.
2017-01-11 13:51:57 -05:00
David Hill
807d344fe9 Unassign some TODO's 2016-11-15 17:47:33 -06:00
Dave Collins
fdfa07b0be
btcec: Consolidate tests into the btcec package.
Putting the test code in the same package makes it easier for forks
since they don't have to change the import paths as much and it also
gets rid of the need for internal_test.go to bridge.

Also, remove the exception from the lint checks about returning the
unexported type since it is no longer required.
2016-10-19 00:55:23 -05:00
Jimmy Song
294b5d46da btcec: Add regression tests for field.go.
This adds new tests to the TestNormalize, TestMul, TestAdd2 functions
which trigger an issue with modular reduction that was fixed in the
prevous commit to prevent regressions.
2016-10-18 16:21:45 -05:00
Dave Collins
a52eb04aaa
btcec: Ensure reduction when > P in all cases.
As noted in issue #706, the existing code had an issue where the
normalized result was > P when both the first and second words of the
field representation being normalized were BOTH greater than or equal to
the first and second words of P.  Although this condition is rare in
practice, it needs to be handled properly.

This resolves the issue by comparing the low words in the final
reduction step against the normalized low order prime bits to ensure the
final subtraction occurs correctly any time they're > P.  This approach
retains the constant time property as well.
2016-10-18 16:21:36 -05:00
Dave Collins
bd4e64d1d4 chainhash: Abstract hash logic to new package. (#729)
This is mostly a backport of some of the same modifications made in
Decred along with a few additional things cleaned up.  In particular,
this updates the code to make use of the new chainhash package.

Also, since this required API changes anyways and the hash algorithm is
no longer tied specifically to SHA, all other functions throughout the
code base which had "Sha" in their name have been changed to Hash so
they are not incorrectly implying the hash algorithm.

The following is an overview of the changes:

- Remove the wire.ShaHash type
- Update all references to wire.ShaHash to the new chainhash.Hash type
- Rename the following functions and update all references:
  - wire.BlockHeader.BlockSha -> BlockHash
  - wire.MsgBlock.BlockSha -> BlockHash
  - wire.MsgBlock.TxShas -> TxHashes
  - wire.MsgTx.TxSha -> TxHash
  - blockchain.ShaHashToBig -> HashToBig
  - peer.ShaFunc -> peer.HashFunc
- Rename all variables that included sha in their name to include hash
  instead
- Update for function name changes in other dependent packages such as
  btcutil
- Update copyright dates on all modified files
- Update glide.lock file to use the required version of btcutil
2016-08-08 14:04:33 -05:00
Mawueli Kofi Adzoe
e8e2167a1a Bump up copyright. Reflect recent update. (#699) 2016-05-22 23:22:42 -05:00
Nathan Bass
f893558d78 Minor correction to GenerateSharedSecret documentation. (#696) 2016-05-14 22:56:29 -05:00
Olaoluwa Osuntokun
3b39edcaa1 txscript: optimize sigcache lookup (#598)
Profiles discovered that lookups into the signature cache included an
expensive comparison to the stored `sigInfo` struct. This lookup had the
potential to be more expensive than directly verifying the signature
itself!

In addition, evictions were rather expensive because they involved
reading from /dev/urandom, or equivalent, for each eviction once the
signature cache was full as well as potentially iterating over every
item in the cache in the worst-case.

To remedy this poor performance several changes have been made:
* Change the lookup key to the fixed sized 32-byte signature hash
* Perform a full equality check only if there is a cache hit which
    results in a significant  speed up for both insertions and existence
checks
* Override entries in the case of a colliding hash on insert Add an
* .IsEqual() method to the Signature and PublicKey types in the
  btcec package to facilitate easy equivalence testing
* Allocate the signature cache map with the max number of entries in
  order to avoid unnecessary map re-sizes/allocations
* Optimize evictions from the signature cache Delete the first entry
* seen which is safe from manipulation due to
    the pre image resistance of the hash function
* Double the default maximum number of entries within the signature
  cache due to the reduction in the size of a cache entry
  * With this eviction scheme, removals are effectively O(1)

Fixes #575.
2016-04-13 21:56:10 -05:00
Dave Collins
eb882f39f8 multi: Fix several misspellings in the comments.
This commit corrects several typos in the comments found by misspell.
2016-02-25 11:17:12 -06:00
Mawuli Adzoe
f5ded65636 Change copyright date for code that was updated this year(2016). 2016-01-07 09:01:51 -07:00
Daniel Martí
829e87a733 Replace *KoblitzCurve by elliptic.Curve
Found via github.com/mvdan/interfacer.
2016-01-03 13:40:26 +01:00
Dave Collins
3942a116e4 docs: Make various README.md files consistent.
First, it removes the documentation section from all the README.md files
and instead puts a web-based godoc badge and link at the top with the
other badges.  This is being done since the local godoc tool no longer
ships with Go by default, so the instructions no longer work without
first installing godoc. Due to this, pretty much everyone uses the
web-based godoc these days anyways.  Anyone who has manually installed
godoc won't need instructions.

Second, it makes sure the ISC license badge is at the top with the other
badges and removes the textual reference in the overview section.

Finally, it's modifies the Installation section to Installation and
Updating and adds a '-u' to the 'go get' command since it works for both
and thus is simpler.
2015-10-23 14:51:36 -05:00
Ishbir Singh
d9556df292 Mitigate timing attacks while using btcec.Decrypt. 2015-05-25 16:42:43 +05:30
Ishbir Singh
58f29ad939 Added ECDH and encryption/decryption support 2015-05-19 23:48:33 +05:30
Dave Collins
6e402deb35 Relicense to the btcsuite developers.
This commit relicenses all code in this repository to the btcsuite
developers.
2015-05-01 12:00:56 -05:00
Oleg Andreev
122031bee3 Makes signing deterministic according to RFC6979 and BIP62. Closes #358. 2015-04-02 09:57:52 +02:00
David Hill
761381066d txscript: Add new verification flags.
This commit adds two new verification flags to txscript named
ScriptVerifyStrictEncoding and ScriptVerifyDerSignatures.

The ScriptVerifyStrictEncoding flag enforces signature scripts
and public keys to follow the strict encoding requirements.

The ScriptVerifyDerSignatures flag enforces signature scripts
to follow the strict encoding requirements.

These flags mimic Bitcoin Core's SCRIPT_VERIFY_STRICTENC and
SCRIPT_VERIFY_DERSIG flags and brings the Bitcoin Core test scripts up
to date.
2015-02-12 12:27:44 -05:00
Dave Collins
f6a437d4c9 btcec: Optimize pre-computed table load.
This commit modifies the pre-computed table used to optimize the secp256k1
scalar multiplication to a string instead of a byte slice.  This change
makes the compile more efficient since the Go compiler internally
represents bytes slices inefficiently.

This reduces the memory needed to compile btcec to 3MB versus the previous
40MB before this change.

In addition, it modifies the code which loads the pre-computed table to
deserialize directly into the table instead of into locals that are then
copied.

Fixes #297.
2015-02-12 00:29:45 -06:00
kargakis
29d3b1ff08 btcec: Fix installation link 2015-02-08 13:20:11 +01:00
Dave Collins
2713c8528d Consistency and general cleanup in btcec.
This commit contains various modifications for code and comment
consistency in the btcec package:
- Call out references at the top and reference them by their identifier in
  the other comments
- Remove a TODO that no longer applies
- Add comments to the fields in the KoblitzCurve struct and reorder them
  slightly
- Make comments wrap to 80
- Cleanup code that was far exceeding col 80 (only function declarations
  typically do this)
- Extend block comments to use as much of the 80 cols as available
- Add a bit more explanation in a couple of places
- Update copyright year on secp256k1.go
- Fix a couple of typos in the comments
2015-02-06 16:55:34 -06:00
Dave Collins
4b84bd52dd Move the btcec benchmarks into the main package.
The benchmarks are still only compiled when running 'go test' so this has
no effect on regular usage.  This is being done because benchmarks often
need access to internal state.

Normal tests are kept in a separate package since they also serve to
exercise the public API, and by intentionally making it more difficult to
reach into the internals, it helps ensure the public API is sanely usable.

Since the benchmarks can now access the internals directly, this commit
also removes the functions which exposed the internals to the test package
from internal_test.go which were only used by the benchmarks.

Also, it removes a duplicate benchmark.
2015-02-06 16:53:29 -06:00
Dave Collins
555778e9d5 Don't ignore errs setting consts in btcec init.
This commit converts the initialization of the constants to use a function
which panics on error instead of just ignoring the error.  This is
acceptable since they are hard-coded constants and should never fail.
2015-02-06 12:57:06 -06:00
Dave Collins
2b25107317 Add generation code for the endomorphism vectors.
This commit adds code which generates the linearly independent vectors
used by the secp256k1 endomorphism code.  These value are hard-coded into
the curve already, but having the code used to generate them is handy
should any future curves be added which can also make use of the same
class of endomorphism.
2015-02-06 12:45:49 -06:00
Dave Collins
8134f68a4b Update TravisCI to ignore false positive in btcec.
Also correct format verb found by go vet.
2015-02-06 10:51:13 -06:00